Pages

Java Modifier Types

Modifiers are keywords that you add to those definitions to change their meanings. The Java language has a wide variety of modifiers, including the following:
To use a modifier, you include its keyword in the definition of a class, method, or variable. The modifier precedes the rest of the statement, as in the following examples
public class className {
   // ...
}
private boolean myFlag;

static final double weeks = 9.5;

protected static final int BOXWIDTH = 42;

public static void main(String[] arguments) {
   // body of method
}
Access Control Modifiers:
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are:

Visible to the package. The default, No modifiers are needed.
  • This means that a java element is not declared as public or private or protected. This default specifier:
  • Will act as public for the same class members or other classes that are in the same path.
  • will act as private for the classes that are defined outside the path
  • will act as protected for the derived classes of same path and outside the path


Visible to the class only (private)
Any java element that is declared as  private can be accessible to the members of  same class only. It cannot be available for  the classes that are in the same path or outside the path.

Visible to the world (public)
Any java element that is declared as public can be accessible to the members of same class or the classes in the same directory or the classes in another path.

Visible to the package and all subclasses (protected)
Any java element that is declared as protected can be accessible to the same  class members or to its sub-classes within the same path or outside the path.

Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.
  • The static modifier for creating class methods and variables
  • The final modifier for finalizing the implementations of classes, methods, and variables.
  • The abstract modifier for creating abstract classes and methods.
  • The synchronized and volatile modifiers, which are used for threads.
Conclusion:

Private
Public
Protected
No modifier
Same class
Yes
Yes
Yes
Yes
Same package Subclass
No
Yes
Yes
Yes
Same package non-subclass
No
Yes
Yes
Yes
Different package subclass
No
Yes
Yes
No
Different package non-subclass
No
Yes
No
NO