A metro rider recharges a card from a phone app. The first version of the app supports one way to pay, a PayKaro wallet, so the code names the PayKaroWallet class wherever a payment appears. A few months later the business wants UPI (Unified Payments Interface) payments too.
The principle says: declare variables, fields, parameters and return types as the type the caller needs, not as the concrete class behind it.
The principle
Every declaration makes a promise about what can go in it. A parameter typed PayKaroWallet accepts a PayKaro wallet and nothing else. A parameter typed PaymentMethod accepts any class that implements it. So we look at what the code calls on the object, and we name a type that offers exactly that.
The concrete class still appears where the object is created with new. Everywhere else, the code names the interface.
What it does not say. It does not mean "write a Java interface for every class". Here "interface" means the set of methods a caller relies on. Sometimes we write that as a Java interface, like PaymentMethod below. Sometimes Java already has one, like List or Map. And when a class has one implementation and no reason to get another, like MetroCard, its public methods are the interface, and callers name the class directly.
This is not the Dependency Inversion Principle. That principle asks whether the business code or the outside code owns the interface between them. This one asks what type each declaration names.
Example: recharging a metro card
The first version names the wallet class in each place a payment passes through:
public class RechargeService { public void recharge(MetroCard card, int amountDollars, PayKaroWallet wallet) { if (!wallet.pay(amountDollars)) { throw new IllegalStateException("Payment refused for card " + card.id()); } card.addBalance(amountDollars); }}AutoTopUp adds $20 when a rider leaves a gate with less than $10 on the card. It keeps the wallet in a field:
public class AutoTopUp { private static final int MINIMUM_DOLLARS = 10; private static final int TOP_UP_DOLLARS = 20; private final RechargeService rechargeService; private final PayKaroWallet wallet; public AutoTopUp(RechargeService rechargeService, PayKaroWallet wallet) { this.rechargeService = rechargeService; this.wallet = wallet; } public void onGateExit(MetroCard card) { if (card.balanceDollars() < MINIMUM_DOLLARS) { rechargeService.recharge(card, TOP_UP_DOLLARS, wallet); } }}PayKaroWallet also has phone() and balanceDollars(), but both callers call only pay.
The change request: add UPI. A new UpiPayment class can pay, but it is not a PayKaroWallet, so neither caller accepts it. The team has two choices. It can change the type in all three declarations: the parameter in recharge, and the field and constructor parameter in AutoTopUp. Or it can add a second recharge and a second auto top-up for UPI, copying the logic. Both choices edit classes whose recharge rules did not change.
Following the principle
We write down the one method the callers use, and the callers name that type:
public interface PaymentMethod { /** Takes the amount from the rider. Returns false if the payment is refused. */ boolean pay(int amountDollars);} public class RechargeService { public void recharge(MetroCard card, int amountDollars, PaymentMethod payment) { if (!payment.pay(amountDollars)) { throw new IllegalStateException("Payment refused for card " + card.id()); } card.addBalance(amountDollars); }}AutoTopUp makes the same change: its field and its constructor parameter become PaymentMethod payment. PayKaroWallet adds implements PaymentMethod, and its pay method stays as it was.
The same request again. UPI is now one new class. UpiGateway is the bank's UPI client:
public class UpiPayment implements PaymentMethod { private final String upiId; private final UpiGateway gateway; public UpiPayment(String upiId, UpiGateway gateway) { this.upiId = upiId; this.gateway = gateway; } @Override public boolean pay(int amountDollars) { return gateway.requestPayment(upiId, amountDollars); }}RechargeService and AutoTopUp do not change. Main builds the objects, so it is the one place that names UpiPayment. A third method, such as a debit card, would be one more class of the same shape.
The same rule with Java's own types
We do not always write the interface ourselves. The first TripHistory declared its list as ArrayList<Trip>. Its trips() method returned that same list, the field itself, as an ArrayList<Trip>, and StatementPrinter stored the result in an ArrayList<Trip> variable. Then a caller cleared a rider's trip history by mistake. The fix is to return a read-only copy with List.copyOf, but that method returns a List, not an ArrayList. With the old types, the fix also changes the return type and every caller's variable. Declared as List, the fix is one line:
public class TripHistory { private final List<Trip> trips = new ArrayList<>(); public void record(Trip trip) { trips.add(trip); } public List<Trip> trips() { return List.copyOf(trips); }}Now a caller's clear() throws UnsupportedOperationException, and the history is safe. Keeping a class's own data out of its callers' hands is the subject of Encapsulation.
When not to
A local variable that never leaves its method can name ArrayList, because no other code sees it. A class with one implementation and no second one in sight, like MetroCard, does not need an interface, and an IMetroCard beside it only adds a file. If a second kind of card appears later, adding the interface then is a one-time edit to the declarations that name the class. Payment methods are different: new ones keep coming, so adding the interface up front saves an edit for each one. When a caller relies on something only one class promises, such as the insertion order of a LinkedHashMap, the declaration should name a type that promises it, such as SequencedMap, or the class itself.
In an interview
In a low-level design (LLD) round, type every field and parameter that holds a swappable part as its interface, and create the concrete class in one place. When the interviewer asks for a new payment method or a new rule, point at the one class you would add. The Parking Lot holds its PaymentProcessor and its pricing and spot rules as interfaces, so each can change without editing ParkingLot.
Common mistakes:
- Casting back to the class.
((PayKaroWallet) payment).phone()ties the caller to PayKaro again, and it fails at run time when the payment is UPI. - Returning a concrete collection. A public method that returns
ArrayList<Trip>orHashMap<String, MetroCard>makes every caller depend on that class. - Creating the object inside the caller. An
AutoTopUpwith aPaymentMethodfield that it sets withnew PayKaroWallet(...)in its own constructor is tied to that wallet again.
Summary
- Declare fields, parameters, return types and variables as the type the caller needs, such as
ListorPaymentMethod. - Name the concrete class only where the object is created.
- The "interface" is the set of methods the caller relies on. It does not have to be a new Java
interface. - Classes with one implementation, and local variables, can name the class directly.