Access Modifiers on Constructors
You'll learn how constructor access modifiers control who can create instances of your class, unlocking powerful design patterns.
The Core Idea
Just like fields and methods, constructors can have access modifiers (private, package-private, public, protected). These modifiers determine which code is allowed to instantiate your class. This isn't just about hiding implementation—it's about controlling how and where objects come into existence.
Why Control Instantiation?
Think of a constructor's access level as a gatekeeper at a building entrance. A public constructor is an open door—anyone can walk in and create an object. A private constructor locks the door entirely—only code inside the class can create instances.
Common Patterns
Public Constructor: The default choice for most classes. Anyone can create instances freely.
public class Customer {
public Customer(String name) { // Anyone can create customers
// initialization
}
}
Private Constructor: Prevents external instantiation. Used for singleton patterns (only one instance allowed) or factory methods (the class controls how it's created).
public class DatabaseConnection {
private DatabaseConnection() { } // No one outside can use 'new'
public static DatabaseConnection getInstance() {
// Factory method controls creation
return new DatabaseConnection(); // OK - we're inside the class
}
}
Package-Private Constructor: Only classes in the same package can instantiate—useful for internal frameworks.
Protected Constructor: Allows subclasses to call via super(), even if they're in different packages, while restricting general instantiation.
Key Takeaway
Constructor access modifiers control who can create objects of your class—private constructors enable singleton and factory patterns by restricting instantiation to the class itself.