Properties (variables and constructors), classes and methods (functions) can have access modifiers to define where they can be accessed. In other words, Access Modifiers are controllers which control a property or method to be accessed. Access modifiers, best described on Oracle Docs
Java access controls are categorised in two levels:
At the top level: public, or package-private (no explicit modifier).
At the member level: public, private, protected, or package-private (no explicit modifier).
In Java, there are four access modifiers:
default: when there is no access control defined with a property or method, it is treated as default modifier. Default modifier is only accessible within the package, it cannot be accessed from outside the package. The default access modifier is also known as package-private.
public – when a property or method is defined with public access control, it can be accessed from everywhere in the same package or outside of the package.
protected – when a property or method is defined with protected access control, it can be accessed within the class and by classes derived from that class.
private – when a property or method is defined with private access control, it can ONLY be accessed within the class.
Below tables well explains Java Access Levels of different entities around Java world:
Modifier | Class | Package | Subclass | World |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
no modifier | Y | Y | N | N |
private | Y | N | N | N |