Confusing Access Modifiers in Java Class and Members
Access Modifiers like Private, Protected, Public can confuse a novice programmer. Access modifiers define where the class or method can be accessed in same class and another classes.
There are two levels of access control.
1. At the Class level – ‘public’ or nothing(package-driven or default)
a. If a class is defined as public, it can be accessed from all the classes anywhere (means from any package).
b. If a class is defined without any modifier, then it is package-driven that means, it is only visible inside the package in which it is defined.
2. At the Data Member level – ‘public’, ‘protected’, ‘private’ or nothing(package-driven or default)
a. If a data member of a class is defined as public as shown below, then it can be seen from anywhere.
i. public int a;
b. If a data member of a class is defined as protected, then it can be accessed only in its class and its child classes.
c. If a data member of a class is defined as private, then it can be only accessed in its class.
d. If a data member is defined without any modifier, then it is package-driven. So, it is visible inside the package where it is defined.
The above rules defined for data member also applies for the methods of a class.
The following table summarizes the rules discussed above.
Access Levels
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