There are four levels of accessibility in Java: public, protected, package, and private. From the blog in JavaPapers.com, I am also summarizing in a table below to show the differences.
Access Level | Same Class | Same Package | Subclasses | Other Packages |
---|---|---|---|---|
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
package | Y | Y | N | N |
private | Y | N | N | N |
Besides, below lists some notes about the access modifier usage and default level.
- Classes can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is package.
- Interfaces can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is also package.
- Class methods and fields can be qualified by all, public, protected, private, or no modifier. When qualified without any modifier, by default the access level is package.
- Interface methods and fields can be qualified by public or no modifier only. When qualified without any modifier, by default the access level is public.
- Inheritance in Java can be public only and this is the default. Unlike C++, there is no protected or private inheritance.
- The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
References
JavaPapers.com
TutorialsPoint
Default access modifier of interface
Inheritance in Java?
Java Tutorial