These are the notes for Low-Level Design (LLD) episode 7, the second episode of the object-oriented design block. We build the checkout of a food-delivery app, watch it break every time a new payment method arrives, and invent the fix step by step: depending on concrete classes (the problem), abstraction, abstraction levels, the interface as a contract, programming to an interface, implementation hiding, the API surface, and abstract class vs interface. Every program was run with javac Main.java && java -cp . Main (Java 21), the same way the SyntaxPilot compiler runs it; outputs and error messages are real.
Quick refresher from episode 3: an interface is a type that lists methods without (usually) saying how they work, and a class implements it; an abstract class is a class marked abstract that can't be created with new. This episode is about why and when to use them in a design.
1. The problem: depending on concrete classes
Priya orders biryani for Rs 250 and pays by UPI (Unified Payments Interface, India's instant bank-to-bank payment system). The first version of our checkout knows every payment class by name.
class UpiPayment {
boolean payViaUpi(String upiId, int amount) {
System.out.println("UPI " + upiId + ": Rs " + amount);
return true;
}
}
class CardPayment {
boolean chargeCard(String cardNo, int amount) {
System.out.println("Card " + cardNo + ": Rs " + amount);
return true;
}
}
class Checkout {
UpiPayment upi = new UpiPayment();
CardPayment card = new CardPayment();
void placeOrder(String mode, int amount) {
if (mode.equals("UPI")) upi.payViaUpi("priya@okbank", amount);
else if (mode.equals("CARD")) card.chargeCard("4111-xx", amount);
else System.out.println("Unknown mode: " + mode);
}
}
public class Main {
public static void main(String[] args) {
Checkout c = new Checkout();
c.placeOrder("UPI", 250);
c.placeOrder("CARD", 400);
c.placeOrder("WALLET", 120);
}
}
UPI priya@okbank: Rs 250
Card 4111-xx: Rs 400
Unknown mode: WALLET
What went wrong. The wallet order was lost, with no error. Checkout depends on concrete classes: real classes you can create with new (UpiPayment, CardPayment). It knows each class's name and each class's method name (payViaUpi, chargeCard), and it chooses between them with an if-else on a mode string. So:
- every new payment method forces an edit to
Checkout(a new field, a new branch); - every edit risks breaking payment methods that already worked;
- a forgotten branch or a typo in a string (
"Card"vs"CARD") silently falls into theelse.
Depending on a class means: if that class changes or a new one appears, your code has to change too.
2. Abstraction
Every car gives you the same few controls: steering, accelerator, brake. Under the bonnet it might be petrol, diesel or electric, and you don't need to know. You learn to drive once and can drive any car.
| Driving a car | In code |
|---|---|
| Steering, accelerator, brake (the same in every car) | What it does: pay(amount) |
| Petrol, diesel or electric engine (hidden) | How it does it: UPI, card, wallet details |
| Learn once, drive any car | Abstraction: one simple idea for many things |
Abstraction means keeping only the essential features of something and hiding the details that don't matter to the person using it. For our checkout, the essential feature of any payment method is one thing: pay this amount, and tell me if it worked.
3. Abstraction levels
Abstraction comes in layers, each built on the one below:
Checkout placeOrder() "the customer wants this order" (high level)
PaymentMethod pay(amount) "move this much money"
Bank API HTTP request "POST /payments ..."
Network bytes 0s and 1s (low level)
- A high abstraction level talks about what the business wants (place an order).
- A low abstraction level talks about how it gets done (requests, bytes).
- API (application programming interface) means the set of things one piece of code offers for other code to call; a "bank API" is the set of web requests a bank accepts. HTTP is the protocol web browsers and servers use to send requests.
- Rule: each layer talks only to the layer just below it. A method that both places an order and opens network connections is mixing levels: it's hard to read (you jump between "business" and "plumbing") and hard to change.
4. The interface as a contract
A wall socket doesn't know about fans or phone chargers. It fixes a standard (pin shape, voltage), and any appliance with the matching plug works. Buying a new appliance never means breaking open the wall.
| Electricity at home | In Java |
|---|---|
| The socket standard | interface PaymentMethod { boolean pay(int amount); } |
| Fan, charger, iron, each with the right plug | Upi, Card, Wallet implements PaymentMethod |
| The wall never changes | Checkout uses only PaymentMethod |
An interface is a list of methods a class promises to provide, without saying how: a contract. Implementing an interface (implements) is signing the contract: the compiler then checks that the class really provides every method.
interface PaymentMethod {
boolean pay(int amount);
}
class Card implements PaymentMethod {
public boolean chargeCard(int amount) {
System.out.println("Card: Rs " + amount);
return true;
}
}
public class Main {
public static void main(String[] args) {
PaymentMethod m = new Card();
m.pay(400);
}
}
Main.java:4: error: Card is not abstract and does not override abstract method pay(int) in PaymentMethod
class Card implements PaymentMethod {
^
1 error
Read the message literally: Card signed the contract (implements PaymentMethod) but has no pay(int), so the only way it could compile is if Card were itself abstract. The fix is to write the method:
public boolean pay(int amount) { ... }
Interface methods are automatically public, so the implementing method must be public too. Leaving it out gives another real error:
interface PaymentMethod {
boolean pay(int amount);
}
class Card implements PaymentMethod {
boolean pay(int amount) { return true; }
}
public class Main {
public static void main(String[] args) { }
}
Output:
Main.java:5: error: pay(int) in Card cannot implement pay(int) in PaymentMethod
boolean pay(int amount) { return true; }
^
attempting to assign weaker access privileges; was public
1 error
Weaker access privileges means the method is less visible than the contract promised.
5. Programming to an interface
Now the redesign. Each payment class signs the contract; Checkout takes any PaymentMethod.
interface PaymentMethod { boolean pay(int amount); }
class Upi implements PaymentMethod {
public boolean pay(int amount) {
System.out.println("UPI: Rs " + amount);
return true;
}
}
class Wallet implements PaymentMethod {
private int balance = 100;
public boolean pay(int amount) {
if (amount > balance) return false;
balance -= amount;
System.out.println("Wallet: Rs " + amount + ", left " + balance);
return true;
}
}
class Checkout {
void placeOrder(PaymentMethod method, int amount) {
System.out.println(method.pay(amount) ? " Placed!" : " Failed");
}
}
public class Main {
public static void main(String[] args) {
Checkout c = new Checkout();
c.placeOrder(new Upi(), 250);
c.placeOrder(new Wallet(), 80);
c.placeOrder(new Wallet(), 120);
}
}
UPI: Rs 250
Placed!
Wallet: Rs 80, left 20
Placed!
Failed
Checkouthas no mode strings, noif-else, and not a single concrete class name.cond ? a : bis the ternary operator, Java's short if-else:aifcondis true, otherwiseb.Walletkeeps its own rule (refuse when the balance is too low) inside itself, as in episode 6.
Programming to an interface (also "program to an interface, not an implementation") means writing your code against the contract, not against a particular class. Adding a new payment option ("PayLater", "gift card") is one new class; Checkout doesn't change at all.
| Depends on concrete classes | Programs to an interface |
|---|---|
UpiPayment upi = new UpiPayment(); inside Checkout |
void placeOrder(PaymentMethod m, int amount) |
if (mode.equals("UPI")) ... else if ... |
m.pay(amount) |
| New method = edit Checkout | New method = new class only |
| Typo in a mode string = silent bug | Missing pay = compile error |
Who creates the concrete objects then? Somebody still writes new Upi(), but only in one place, at the edge of the program (here, main). Episode 16 (Dependency Inversion) turns this into a rule.
6. Implementation hiding
interface PaymentMethod {
boolean pay(int amount);
}
class Upi implements PaymentMethod {
private final String upiId;
Upi(String upiId) { this.upiId = upiId; }
String upiId() { return upiId; }
public boolean pay(int amount) { return true; }
}
class Checkout {
void placeOrder(PaymentMethod method, int amount) {
System.out.println("Paying from " + method.upiId());
method.pay(amount);
}
}
public class Main {
public static void main(String[] args) {
new Checkout().placeOrder(new Upi("priya@okbank"), 250);
}
}
Main.java:12: error: cannot find symbol
System.out.println("Paying from " + method.upiId());
^
symbol: method upiId()
location: variable method of type PaymentMethod
1 error
Checkout sees the object only through the PaymentMethod type, and that type has no upiId(). Implementation hiding means that users of an interface see only its methods; every detail of each implementation stays out of reach. That's a feature: if Checkout could call upiId(), it would break the day a Card was passed in.
If every payment method really needs to describe itself, add it to the contract (for example String label();) so every implementation must provide it.
7. The API surface
A restaurant gives you a menu, not a tour of the kitchen.
| At a restaurant | In code |
|---|---|
| The menu (what you can order) | API surface: every public type, method and field |
| The kitchen (recipes, staff, suppliers) | The implementation: private fields and helpers |
| A short menu is easier to keep every promise of | Keep the surface small |
The API surface of a class or library is everything other code can use. Every public method is a promise: once others depend on it, removing or changing it breaks them. So:
- make
publiconly what callers truly need; keep helpersprivate; - expose interfaces (
PaymentMethod,List) rather than concrete classes; - return the most general type that is useful (
List<String>, notArrayList<String>).
8. Depending on concrete classes in everyday Java
import java.util.*;
public class Main {
static void printMenu(ArrayList<String> items) {
for (String item : items) System.out.println("- " + item);
}
public static void main(String[] args) {
ArrayList<String> lunch = new ArrayList<>(List.of("Biryani", "Dosa"));
printMenu(lunch);
printMenu(List.of("Chai", "Samosa"));
}
}
Main.java:10: error: incompatible types: no instance(s) of type variable(s) E exist so that List<E> conforms to ArrayList<String>
printMenu(List.of("Chai", "Samosa"));
^
where E is a type-variable:
E extends Object declared in method <E>of(E,E)
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
The message is long because List.of is generic (it works for any element type E), but it means: a List is not an ArrayList. printMenu only loops over items, yet it demanded one specific class. Program to the interface:
import java.util.*;
public class Main {
static void printMenu(List<String> items) {
for (String item : items) System.out.println("- " + item);
}
public static void main(String[] args) {
List<String> lunch = new ArrayList<>(List.of("Biryani", "Dosa"));
printMenu(lunch);
printMenu(List.of("Chai", "Samosa"));
printMenu(new LinkedList<>(lunch));
}
}
- Biryani
- Dosa
- Chai
- Samosa
- Biryani
- Dosa
Rule of thumb: declare variables, parameters and return types with interface types (List, Set, Map, Queue); name the concrete class (ArrayList, HashSet, HashMap, ArrayDeque) only after new:
List<String> orders = new ArrayList<>();
Map<String, Integer> stock = new HashMap<>();
9. Abstract class vs interface
A new requirement: every payment must reject amounts of zero or less, and write a log line. With only an interface, each class copies those steps:
interface PaymentMethod {
boolean pay(int amount);
}
class Upi implements PaymentMethod {
public boolean pay(int amount) {
if (amount <= 0) throw new IllegalArgumentException("Bad: " + amount);
System.out.println("[log] paying Rs " + amount);
System.out.println("UPI: Rs " + amount);
return true;
}
}
class Card implements PaymentMethod {
public boolean pay(int amount) {
System.out.println("[log] paying Rs " + amount);
System.out.println("Card: Rs " + amount);
return true;
}
}
public class Main {
public static void main(String[] args) {
new Upi().pay(250);
new Card().pay(-50);
}
}
[log] paying Rs 250
UPI: Rs 250
[log] paying Rs -50
Card: Rs -50
Card copied the log line but forgot the check, so a payment of Rs -50 went through. An interface states what to do, but it can't hold the shared steps (and it can't hold fields).
A chai franchise gives every outlet a recipe card with fixed steps (boil, add tea, strain, serve) and lets each outlet add its own special (masala, ginger). There's no outlet called just "Franchise".
| Chai franchise | In Java |
|---|---|
| Fixed steps for every outlet | public final boolean pay(int amount): check + log, once |
| Each outlet's own special | protected abstract boolean charge(int amount) |
| No outlet called "Franchise" | abstract class: can't be created with new |
An abstract class is a half-built class: it can hold fields, constructors and finished methods, plus abstract methods (no body) that each subclass must fill in. Words used here:
extends: "builds on";class Upi extends BasePaymentmakesUpia subclass that gets everythingBasePaymenthas (episode 8 covers this fully).finalon a method: subclasses can't replace it, so nobody can skip the check.protected: visible to subclasses (and the same package), not to everyone.- Instantiate: create an object of a class with
new.
interface PaymentMethod {
boolean pay(int amount);
}
abstract class BasePayment implements PaymentMethod {
public final boolean pay(int amount) {
if (amount <= 0) throw new IllegalArgumentException("Bad: " + amount);
System.out.println("[log] paying Rs " + amount);
return charge(amount);
}
protected abstract boolean charge(int amount);
}
class Upi extends BasePayment {
protected boolean charge(int amount) {
System.out.println("UPI: Rs " + amount);
return true;
}
}
class Card extends BasePayment {
protected boolean charge(int amount) {
System.out.println("Card: Rs " + amount);
return true;
}
}
public class Main {
public static void main(String[] args) {
PaymentMethod p = new BasePayment();
}
}
Main.java:26: error: BasePayment is abstract; cannot be instantiated
PaymentMethod p = new BasePayment();
^
1 error
interface PaymentMethod {
boolean pay(int amount);
}
abstract class BasePayment implements PaymentMethod {
public final boolean pay(int amount) {
if (amount <= 0) throw new IllegalArgumentException("Bad: " + amount);
System.out.println("[log] paying Rs " + amount);
return charge(amount);
}
protected abstract boolean charge(int amount);
}
class Upi extends BasePayment {
protected boolean charge(int amount) {
System.out.println("UPI: Rs " + amount);
return true;
}
}
class Card extends BasePayment {
protected boolean charge(int amount) {
System.out.println("Card: Rs " + amount);
return true;
}
}
public class Main {
public static void main(String[] args) {
new Upi().pay(250);
new Card().pay(-50);
}
}
[log] paying Rs 250
UPI: Rs 250
Exception in thread "main" java.lang.IllegalArgumentException: Bad: -50
at BasePayment.pay(Main.java:6)
at Main.main(Main.java:27)
The check now lives in one place and no subclass can forget it. (This "fixed skeleton + abstract steps" shape is the Template Method pattern, episode 38.)
| Interface | Abstract class | |
|---|---|---|
| Purpose | A contract: what | A half-built class: shared how |
| Instance fields | No (only constants) | Yes |
| Constructors | No | Yes |
| Method bodies | default and static methods (since Java 8) |
Any methods |
| How many per class | A class can implement many | A class can extend one |
| Who shares it | Even unrelated classes | Closely related classes |
| Typical use | The type callers depend on | Sharing code behind that type |
Best of both: callers depend on the interface (PaymentMethod); an abstract class behind it (BasePayment) shares the common code; concrete classes fill in the differences. The JDK does exactly this: List (interface) ← AbstractList (abstract class) ← ArrayList.
The class diagram
Checkout - - - - uses - - - -> «interface» PaymentMethod
+ pay(amount): boolean
^
: (implements, dashed + hollow triangle)
«abstract» BasePayment
+ pay(amount) {final}
# charge(amount) {abstract}
^ ^
(extends) Upi Card
+ public, - private, # protected. A dashed arrow is a dependency ("uses"), a dashed line with a hollow triangle is realization (implements), a solid line with a hollow triangle is inheritance (extends).
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
if-else on mode strings in Checkout |
no error: Unknown mode: WALLET |
Depends on concrete classes | Take a PaymentMethod and call pay() |
implements PaymentMethod without pay |
error: Card is not abstract and does not override abstract method pay(int) in PaymentMethod |
The contract wasn't kept | Write public boolean pay(int amount) |
Implementing without public |
error: pay(int) in Card cannot implement pay(int) in PaymentMethod ... attempting to assign weaker access privileges; was public |
Interface methods are public | Add public |
| Calling an implementation method through the interface | error: cannot find symbol ... location: variable method of type PaymentMethod |
Only the contract is visible | Add it to the contract, or don't depend on it |
A parameter typed as ArrayList |
error: incompatible types: no instance(s) of type variable(s) E exist so that List<E> conforms to ArrayList<String> |
Demands one concrete class | Use List<String> |
new on an abstract class |
error: BasePayment is abstract; cannot be instantiated |
It's half-built | Create a concrete subclass (new Upi()) |
| Copying shared steps into each class | no error: Card: Rs -50 |
One copy forgot the check | Shared steps in an abstract class, final |
Mini project
Design a notification sender for the delivery app. Orders must notify the customer by SMS, email or push notification, and next month marketing will add WhatsApp. Requirements: OrderService must not change when a channel is added; every message must be trimmed and must not be empty (checked in one place); each channel formats the message its own way.
Solution
import java.util.*;
interface Notifier {
void send(String to, String message);
}
abstract class BaseNotifier implements Notifier {
public final void send(String to, String message) {
String m = message.trim();
if (m.isEmpty()) throw new IllegalArgumentException("Empty message");
deliver(to, m);
}
protected abstract void deliver(String to, String message);
}
class Sms extends BaseNotifier {
protected void deliver(String to, String m) { System.out.println("SMS to " + to + ": " + m); }
}
class Email extends BaseNotifier {
protected void deliver(String to, String m) { System.out.println("Email to " + to + ": [Order] " + m); }
}
class Push extends BaseNotifier {
protected void deliver(String to, String m) { System.out.println("Push to " + to + ": " + m); }
}
class OrderService {
private final List<Notifier> notifiers;
OrderService(List<Notifier> notifiers) { this.notifiers = List.copyOf(notifiers); }
void orderPlaced(String customer) {
for (Notifier n : notifiers) n.send(customer, " Your biryani is on the way! ");
}
}
public class Main {
public static void main(String[] args) {
OrderService service = new OrderService(List.of(new Sms(), new Email(), new Push()));
service.orderPlaced("Priya");
new Sms().send("Priya", " ");
}
}
Output:
SMS to Priya: Your biryani is on the way!
Email to Priya: [Order] Your biryani is on the way!
Push to Priya: Your biryani is on the way!
Exception in thread "main" java.lang.IllegalArgumentException: Empty message
at BaseNotifier.send(Main.java:9)
at Main.main(Main.java:34)
OrderService depends only on Notifier; a WhatsApp class is one new subclass. The trim-and-check rule lives in BaseNotifier.send, which is final.
Practice
- Which of these lines program to an interface? (a)
ArrayList<Order> list = new ArrayList<>();(b)Map<String, Integer> stock = new HashMap<>();(c)HashSet<String> tags = new HashSet<>();(d)Queue<Order> q = new ArrayDeque<>();
Solution
(b) and (d). In (a) and (c), every line that uses the variable can depend on ArrayList/HashSet-only methods, so switching later is harder.
- A
ReportServicehasvoid export(String format)withif (format.equals("PDF")) ... else if (format.equals("CSV")) .... Redesign it.
Solution
interface Exporter { byte[] export(Report r); } with PdfExporter and CsvExporter; ReportService takes an Exporter (or a Map<String, Exporter> if the user picks the format at run time). A new format is a new class.
- Interface or abstract class? (a) "Anything that can be printed" for invoices, tickets and labels; (b) three kinds of bank account that share a balance field and the same withdraw checks.
Solution
(a) An interface Printable: unrelated classes, a contract only. (b) An abstract class Account with the balance and a final withdraw holding the checks (ideally behind an Account interface that callers use).
- Why does
Checkoutin section 6 fail to compile, even though the object passed in really is aUpithat hasupiId()?
Solution
The compiler only allows calls the declared type (PaymentMethod) offers. The actual object's class doesn't matter at compile time. That is implementation hiding.
- Spot the mixed abstraction levels:
void placeOrder(Order o) { validate(o); Socket s = new Socket("bank.example", 443); s.getOutputStream().write(...); sendConfirmation(o); }
Solution
Opening a socket and writing bytes is network-level work inside business-level code. Move it behind PaymentMethod.pay(...) (and further down, a bank client class), so placeOrder reads: validate, pay, confirm.
Quick quiz
A delivery app needs a list of orders. Which declaration programs to an interface?
ArrayList<Order> o = new ArrayList<>();List<Order> o = new ArrayList<>();Object o = new ArrayList<Order>();var o = new ArrayList<Order>();
Answer
List<Order> o = new ArrayList<>(); The rest of the code sees only the List contract, so it can switch to another List later. ArrayList and var (which infers ArrayList) lock you to the class, and Object hides too much: you can't even call add.
Interview questions
- What is abstraction? Exposing only the essential behaviour of something and hiding the details that don't matter to its users, so they can work at a higher level.
- Abstraction vs encapsulation? Abstraction decides what to show (the essential operations); encapsulation is how you protect the rest (private data behind methods). Abstraction is about the design of the outside; encapsulation about guarding the inside.
- What does "program to an interface, not an implementation" mean? Declare variables, parameters and return types with interface types and call only contract methods, so implementations can be swapped or added without changing the caller.
- Interface vs abstract class? Interface: a contract, no instance state, a class can implement many, usable by unrelated classes. Abstract class: shared state and code for closely related classes, constructors allowed, single inheritance. Commonly: an interface for callers, an abstract class behind it for shared code.
- Can an interface have method bodies? Yes,
defaultandstaticmethods since Java 8 (andprivatehelper methods since Java 9), but no instance fields. - Why is
List<String> x = new ArrayList<>()preferred? Code usingxdepends only onList, so you can change the implementation in one place. - What is an API surface and why keep it small? Everything public that others can use; each public element is a promise you must keep, so a smaller surface is easier to maintain and change.
- What is a symptom of depending on concrete classes?
if-else/switchon type names or mode strings,new ConcreteClass()scattered inside business logic, and many files changing when one new variant is added.
Glossary
| Term | Meaning, with an example |
|---|---|
| Abstraction | Keeping only the essential features and hiding the rest. A car's steering and pedals; pay(amount) for any payment |
| Abstraction level | How close code is to the business (high) or to the machine (low). placeOrder() is high, sending bytes is low |
| Mixing levels | One method doing high-level and low-level work. Placing an order and opening a socket in the same method |
| Concrete class | A complete class you can create with new. UpiPayment, ArrayList |
| Depending on concrete classes | Code that names specific classes, so it must change when they change or new ones appear. Checkout's if (mode.equals("UPI")) |
| Mode string / type code | A string or number used to say what kind of thing something is. "UPI", "CARD" |
| Interface | A type listing methods a class promises to provide. interface PaymentMethod { boolean pay(int amount); } |
| Contract | The promise an interface represents: these methods, with these parameters and return types |
implements |
Signs a contract: class Upi implements PaymentMethod |
| Programming to an interface | Writing code against interface types, not specific classes. void placeOrder(PaymentMethod m, ...) |
| Implementation | The actual code that fulfils a contract. Upi.pay printing a UPI payment |
| Implementation hiding | Callers see only the contract's methods, never the implementation's details. method.upiId() doesn't compile |
| API (application programming interface) | The set of things code offers for other code to call. A bank's payment requests; a class's public methods |
| API surface | Everything public that others can use. Keep it small |
| HTTP | The protocol browsers and servers use to send requests and responses |
| Ternary operator | cond ? a : b, a short if-else expression. ok ? "Placed!" : "Failed" |
| Generic | Works with any type, written with a type parameter like <E>. List.of(...), List<String> |
List / ArrayList / LinkedList |
An interface for ordered collections / two classes that implement it |
| Abstract class | A half-built class marked abstract: fields and finished methods plus abstract methods; can't be instantiated. BasePayment |
| Abstract method | A method with no body that subclasses must implement. protected abstract boolean charge(int amount); |
extends |
Makes a class a subclass of another and inherits its members. class Upi extends BasePayment |
final method |
A method subclasses can't override. public final boolean pay(...) |
protected |
Visible to subclasses and the same package |
| Instantiate | Create an object of a class with new. new Upi() |
| Default method | An interface method with a body, marked default (Java 8+) |
| Dependency (UML) | Dashed arrow with an open head: one class uses another |
| Realization (UML) | Dashed line with a hollow triangle: a class implements an interface |
| Inheritance (UML) | Solid line with a hollow triangle: a class extends another |
Summary
- Code that knows concrete classes by name (mode strings,
if-else,neweverywhere) must be edited for every new variant. - Abstraction keeps the essentials and hides the rest; organise code in abstraction levels, each talking to the one below.
- An interface is a contract the compiler checks; program to the interface so new implementations plug in without changes.
- Implementation hiding: callers see only the contract. Keep the API surface small.
- Declare
List,Map,Set; useArrayList,HashMap,HashSetonly afternew. - Interface = what (many per class, no state); abstract class = shared how (one per class, fields + final steps). Use both together.
Next episode: OOP 3: inheritance done right.