Tutorials

Object Oriented Programming


Access Modifiers


Access modifier in java is used to define the scope or visibility of the entity to which it is applied.

We have four access modifiers in java:

  • Public
  • Private
  • Protected
  • Default*

*If any of the first three access modifier is not applied then java provides default access modifier itself. 

You can apply any of the above modifiers can be used with any of the following:

  • Class
  • Variables
  • Methods
  • Constructors

We will learn about each of the access modifiers one by one.

 

Public Access Modifier

A class or variable or method or constructor or interface declared as public is accessible to any other class from same package or outside the package.

Important points on public modifier

  • Members declared public has widest scope and visibility.
  • A class declared as public can be inherited by other classes.

 

Why main method is public?

Because main() method needs to be called by JVM when program is executed. If it is declared with other access modifier then JVM will not be able to access the main() method and program would not get executed as it is the entry point for java program.

 

 

Private Access Modifier

A class or variable or method or constructor declared as public is accessible only within the same class.

Important points on public modifier

  • You cannot access private members from outside the class.
  • Members declared as private have restrictive scope and visibility. So it’s not wise to declare a class or interface as private.
  • A variable declared private cannot be accessed directly from other class. Rather these variables can only be accessed using public getter method of the class in which variable is declared. This is how encapsulation is achieved. For more read Encapsulation section.

 

Protected Access Modifier

A variable or method or constructor declared as protected is accessible by any class within the same package or the subclass of the class located in other package.

Important points on public modifier

  • You cannot declare a class or interface as protected.
  • Methods and variables in interface cannot be declared protected.

 

Default Access Modifier

When we do not apply any access modifier then a default modifier is provided by java.

Important points on public modifier

  • Members declared with default access specifiers can be accessed by same class.

  • Members declared with default access specifiers can be accessed by any other class in the same package

 

Access Modifier Visibility chart

Access Modifier

Same class

Other class in same package

Subclass from other package

Other Package

public

Yes

Yes

Yes

Yes

private

Yes

No

No

No

protected

Yes

Yes

Yes

No

default

Yes

Yes

No

No

 



Please Share this page
Views : 60