Pages

Access Modifiers


Because method and variable members are usually given access control in exactly the same way. Whereas a class can use just two of the four access control levels, members can use all four: Public, Private, Protected, Default.

Public

Definition : Public members of a class are accessible everywhere outside the class. So, any other program can read them and use them.
Rules :
  1. Public can be applied to variables.
  2. Public can be applied to methods.
  3. Public can be applied to classes.

Private

Definition : Private members of a class are not accessible anywhere outside the class. They are accessible only within the class by the methods of that class.
Rules :
  1. Private can be applied to variables.
  2. Private can be applied to methods.
  3. Private cannot be applied to classes.

Protected

Definition : Protected members of a class are accessible outside the class, but generally, within the same directory (Package). Protected members can be accessed by a subclass is in a different package through inheritance.
Rules :
  1. Protected can be applied to variables.
  2. Protected can be applied to methods.
  3. Protected cannot be applied to classes.

Default

Definition : If no access specifier is written by the programmer, then the Java compiler uses a ‘default’ access specifier. ‘Default’ members are accessible outside the class, but within the same directory (Package).
Rules :
  1. Default can be applied to variables.
  2. Default can be applied to methods.
  3. Default can be applied to classes.

Write the Access Modifiers in the increasing order of their visibility ?

Private -----> Default -----> Protected -----> Public.

Method Overriding Rules in Access Modifiers

Rules :
  1. If super class method is public while overriding it in child class, it should be public. Since, it is the weakest access specifier or least restrictive access specifier.
  2. If super class method is protected while overriding it in child class, it can be public or protected but not anything else.
  3. If super class method is default then while overriding it in child class, it can be public, protected and default but can not be private.
  4. If super class method is private then while overriding it in child class it can be anything, since private method can not be overrided.

Can be applied to Class, Methods, Instance Variables, Static Variables, Local Variables


Access Modifiers Class Method Instance Variables Static Variables Local Variables
Public Yes Yes Yes Yes No
Private No Yes Yes Yes No
Protected No Yes Yes Yes No
Default Yes Yes Yes Yes Yes


Determining Access to Class Members


Visibility Public Private Protected Default
From the same class Yes Yes Yes Yes
From any class in the same package Yes Yes Yes No
From a subclass in the same package Yes Yes Yes No
From a subclass outside the same package Yes Yes, through inheritance No No
From any non-subclass class outside the package Yes No No No