Public Interfaces, Package-Private Implementations
You'll learn how to design flexible systems by exposing public contracts while hiding concrete implementations from external packages.
The Pattern
This is one of the most powerful access control strategies in Java: define a public interface that announces what your code can do, but keep the classes that implement it package-private. External code depends only on the interface, never the concrete class.
Why it works:
When you expose a public interface, other packages can use that type in their code. But by making the implementing class package-private (default access), you prevent external code from directly instantiating or depending on the specific implementation. This gives you flexibility to change, replace, or refactor the implementation without breaking any external code.
Think of it like ordering at a restaurant: the menu (interface) is public, but the kitchen staff and recipes (implementations) are hidden. You order "pasta"—you don't need to know which chef makes it or what brand of flour they use. The restaurant can swap chefs or techniques without you noticing.
How It Looks
// Public interface - exposed to all packages
public interface PaymentProcessor {
boolean processPayment(double amount);
}
// Package-private implementation - hidden from other packages
class CreditCardProcessor implements PaymentProcessor {
public boolean processPayment(double amount) {
// implementation details
return true;
}
}
External packages can use PaymentProcessor as a type, but they cannot directly create CreditCardProcessor instances. You control object creation through factory methods or constructors in other public classes within your package.
Key Takeaway: Expose public interfaces to define contracts; keep implementations package-private to maintain flexibility and prevent external coupling to specific classes.