Introduction

In this article, I am explaining Access Modifiers keywords in Java.
In access modifiers there are mainly the following three keywords:
  1. Private
  2. Protected
  3. Public
Here's the explanation:

Java Access Modifier - Private Keyword

The private keyword is an access modifier that can be applied to a method, member variable and inner class.

Java Access Modifier - Protected Keyword

The protected keyword is an access modifier for method and variable of a class. When a method or a variable is marked protected, it can be accessed from the following:
The main purpose of protected keyword is to have the method or variable that can be inherited from sub classes.
Example
The following class Person declares a protected variable name, inside package p1:
  1. package p1;
  2. public class Person {
  3. protected String name;
  4. }
The following class in the same package can access the variable name directly:
  1. package p1;
  2. public class Employer {
  3. void hireEmployee() {
  4. Person p = new Person();
  5. p.name = "Nam"; // access protected variable directly
  6. }
  7. }
The following class is in different packages but it extends the Person class so it can access the variable name directly:
  1. package p2;
  2. import p1.Person;
  3. class Employee extends Person {
  4. void doStuff() {
  5. name = "Bob";
  6. }
  7. }
But the following class in different package cannot access the variable name directly:
  1. package p2;
  2. import p1.Person;
  3. class AnotherEmployer {
  4. void hire() {
  5. Person p = new Person();
  6. // compile error, cannot acceess protected variable
  7. // from different package
  8. p.name = "Nam";
  9. }
  10. }

Java Access Modifier - Public keyword

The public keyword is an access modifier for class, method and variable:
To summarize, public is the access modifier that has least restriction on the object it modifies.
The following code example shows a public class which has a public method eat() and a public variable name:
  1. public class Person {
  2. public String name;
  3. public void eat() {}
  4. }