Access specifiers in Java
Modifier | Class | Package | Subclass | World ————————————+———————+—————————+——————————+——————— public | ✔ | ✔ | ✔ | ✔ ————————————+———————+—————————+——————————+——————— protected | ✔ | ✔ | ✔ | ✘ ————————————+———————+—————————+——————————+——————— no modifier | ✔ | ✔ | ✘ | ✘ ————————————+———————+—————————+——————————+——————— private | ✔ | ✘ | ✘ | ✘
Summary
Is an access to a member with this access specifier allowed?
- Member is
private: Only if member is defined within the same class as calling code. - Member is package private: Only if the calling code is within the member's immediately enclosing package.
- Member is
protected: Same package, or if member is defined in a superclass of the class containing the calling code. - Member is
public: Yes.
What access specifiers apply to
Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.
For classes in the top scope, only
public and package-private are permitted. This design choice is presumably because protected and private would be redundant at the package level (there is no inheritance of packages).
All the access specifiers are possible on class members (constructors, methods and static member functions, nested classes).
Related: Java Class Accessibility
Order
The access specifiers can be strictly ordered
public > protected > package-private > private
meaning that
public provides the most access, private the least. Any reference possible on a private member is also valid for a package-private member; any reference to a package-private member is valid on a protected member, and so on. (Giving access to protected members to other classes in the same package was considered a mistake.)