Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A package-private method in Java is a method declared without an explicit access modifier, restricting its visibility and invocation strictly to classes residing within the exact same package. It represents the default access control level in the Java language, often referred to as “default access” or “package access.”

Syntax

To declare a package-private method, omit the public, protected, and private keywords from the method signature.
package com.example.core;

public class Processor {
    
    // Package-private method
    void executeTask() {
        // Method implementation
    }
}

Visibility Matrix

The Java compiler and the JVM access control mechanism enforce the following visibility rules for package-private methods:
ContextAccessible?
Same ClassYes
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.
package com.example.core;

public class BaseProcessor {
    void process() {} // Package-private
}

class AdvancedProcessor extends BaseProcessor {
    @Override
    protected void process() {} // Legal: Access widened to protected
}
Interface Context Exception The package-private access level does not apply to interface methods. Omitting an access modifier on a method declaration within an interface implicitly makes the method public, not package-private.
package com.example.core;

public interface Executable {
    void run(); // Implicitly public, NOT package-private
}
Master Java with Deep Grasping Methodology!Learn More