Syntax
To declare a package-private method, omit thepublic, protected, and private keywords from the method signature.
Visibility Matrix
The Java compiler and the JVM access control mechanism enforce the following visibility rules for package-private methods:| Context | Accessible? |
|---|---|
| Same Class | Yes |
| Same Package (Subclass) | Yes |
| Same Package (Non-subclass) | Yes |
| Different Package (Subclass) | No |
| Different Package (Non-subclass) | No |
Technical Characteristics
Inheritance and Overriding A package-private method is only inherited by subclasses located within the same package. Consequently, it can only be overridden by subclasses in the same package. If a subclass in a different package declares a method with the identical signature, it does not override the superclass’s package-private method. Instead, the compiler treats it as a completely independent method. The@Override annotation will trigger a compile-time error in this cross-package scenario.
Access Privilege Elevation
When overriding a package-private method within the same package, the subclass can maintain the package-private access level or widen it to protected or public. The Java Language Specification dictates that an overriding method cannot narrow the access privileges of the overridden method.
interface implicitly makes the method public, not package-private.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More





