Java provides with various access modifiers to class, methods, variables, constructors to set access level and control who can access which variables or class or methods.
The Access levels are divided into below categories
- Public >> Access to everyone
- Private >> Access to enclosing class
- Protected >> Access to all subclass and within the package
- default >> Access to all classes within the package
Lets see how these modifiers affect the its functionality when applied to different key aspects of JAVA
Public | Private | Protected | Default (No modifier) | |
Class | Acesss to everyone | NA | NA | Access to classes within package |
Variable | Acess to everyone | Access to enclosing class members | Access within package and subclass | Access to classes within package |
Method | Acess to everyone | Access to enclosing class members | Access within package and subclass | Access to classes within package |
Constructor | Acess to everyone | Access to enclosing class members | Access within package and subclass | Access to classes within package |
There is another keyword “final” which can be applied to a Class, Variable, Method. Although it does not determine the access but it has great significance.
When applied to a class it means, the class cannot be subclassed, i.e. extending a class marked final is not possible. A small example is described below. The keyword can be placed before or after the access modifier.
public final class Car {
}
The final keyword when applied to method of a class, makes the method final and does not allow the subclasses to be override.
And the final keyword when applied to a variable implies that the variable cannot be reassigned to a new instance once it is assigned a value.