Java Access Modifiers or Access Controls

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:

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
no modifierYYNN
privateYNNN
This table defines levels of access conferred by a modifier.

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2024 Faraz Jafri All rights reserved. Privacy Policy

Proudly powered by WordPress. Special thanks to Bootstrap, FontAwesome & Open Source Community.