A package-private constructor in Java is a constructor declared without any explicit access modifier (such asDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
public, private, or protected). It restricts the instantiation of the class strictly to other classes residing within the exact same package, enforcing package-level access control at the point of object creation.
Syntax
To define a package-private constructor, omit the access modifier entirely from the constructor declaration:Access Control Rules
The absence of an access modifier applies Java’s “default” (package-private) visibility rules specifically to the constructor, independent of the class’s visibility. Even if the class itself is declaredpublic, a package-private constructor imposes the following restrictions:
- Same Package Access: Any class located in the same package can invoke the constructor using the
newkeyword. - Cross-Package Restriction: Classes located in a different package cannot invoke the constructor. Attempting to do so results in a standard
javaccompile-time error:ClassName(...) is not public in ClassName; cannot be accessed from outside package. - Subclassing Constraints: If a superclass only defines package-private constructors, it cannot be subclassed by a class in a different package. Subclass constructors must invoke a superclass constructor (implicitly or explicitly via
super()). If the superclass constructor is package-private, it is invisible to the cross-package subclass, causing a compilation failure.
Code Visualization
The following example demonstrates the compilation boundaries enforced by a package-private constructor across distinct files:Node.java
NodeManager.java
Application.java
Implicit Constructor Behavior
If a class declares no constructors, the Java compiler automatically generates a no-argument default constructor. For standard classes, the access modifier of this compiler-generated constructor strictly matches the access modifier of the class itself. However, if the type is anenum, the implicitly generated default constructor is always private, regardless of the enum’s access modifier (per JLS 8.9.2).
Therefore, if a standard class is public, its implicit default constructor is public. To enforce package-private instantiation on a public class, the package-private constructor must be explicitly declared to override the compiler’s default behavior.
Master Java with Deep Grasping Methodology!Learn More





