Access modifier

  • Eclipse: Oxygen
  • Java: 1.8

Access modifiers in Java help to restrict the scope of a class, constructor, variable, method and data member.

There are four types of access modifiers:

  1. Private
  2. Public
  3. Protected
  4. Default – No keyword is required

The private access modifier is specified using the private keyword. It is accessible only within the class.

In private access modifier, methods or data members declared as private are accessible only within the class in which they are declared. Any other class in the same package will not be able to access these members. Classes or the top-level interface cannot be declared private because of private means “only visible within the attached class”.

In this example, we will create two packages org.studyeasy.parent and org.studyeasy.child. Class A in org.studyeasy.parent is made public, to access it in org.studyeasy.child. The variable display in class A is private and class B is inherited from class A and this private variable is then accessed by creating an object of class A.


Value of x is 10

The public variable is visible everywhere in contrast to the private variable which is local variable to a class and protected variable which is also not visible in the different classes until It has the same package.

The public access modifier is specified by the keyword public. You can access classes, methods or data members that are declared public from anywhere in the program. There are no restrictions on the scope of public data members.


Value of x is 10


Default access modifier:

In general default access modifier is accessible only within the package. If you do not use any modifier, it will be treated as default.

Protected access modifier:

The protected access modifier is accessible within the package and outside the package but only through inheritance. It can be applied to the data member, the method, and the constructor. It cannot be applied in the class.

Let’s understand the access modifiers by the following table.

Contributed by: Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu