SyntaxPilot
Courses/Low-Level Design/Lesson 3

Low-Level Design · Lesson 3 of 90 · 16 min

Java for LLD 2: interfaces, enums, records and generics

interfaceimplementsdefault methodsstatic interface methodsabstract classabstract methodenumenum with fields and methodsEnumMaprecordcompact constructorgenericstype parameterbounded types

These are the notes for Low-Level Design (LLD) episode 3. Classes alone are not enough for good designs. This episode adds four tools, each invented as the fix for a bug in a food-delivery app: interfaces (with implements, default methods and static interface methods), abstract classes and abstract methods, enums (with fields, methods and EnumMap), records (with the compact constructor), and generics (type parameters, bounded types, wildcards and type erasure). 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.

1. Interfaces

The problem: payment type as a String

public class Main {
    static void pay(String method, int amount) {
        if (method.equals("UPI")) System.out.println("UPI: Rs " + amount);
        else if (method.equals("CARD")) System.out.println("Card: Rs " + amount);
        else System.out.println("Unknown payment: " + method);
    }
    public static void main(String[] args) {
        pay("UPI", 250);
        pay("upi", 180);
        pay("Card", 400);
    }
}
UPI: Rs 250
Unknown payment: upi
Unknown payment: Card

A String can hold any text, so the compiler cannot check it: typos become failed payments at run time. And every new payment type (wallet, cash) means editing the if chain again.

The fix: an interface

An interface is like a job description: "must be able to deliver". It lists methods with no body; any class that takes the job with implements must write every one of them. The caller only knows the job, not who does it.

interface PaymentMethod {
    void pay(int amount);
}
class Upi implements PaymentMethod {
    public void pay(int amount) { System.out.println("UPI: Rs " + amount); }
}
class Card implements PaymentMethod {
    public void pay(int amount) { System.out.println("Card: Rs " + amount); }
}
public class Main {
    static void checkout(PaymentMethod m, int amount) { m.pay(amount); }
    public static void main(String[] args) {
        checkout(new Upi(), 250);
        checkout(new Card(), 400);
    }
}
UPI: Rs 250
Card: Rs 400
  • Interface methods are public (and abstract) automatically, so implementing methods must be public.
  • checkout takes the interface type, so it works with any present or future payment class.
  • A typo is now a compile error:
Main.java:14: error: cannot find symbol
        checkout(new Crad(), 400);
                     ^
  symbol:   class Crad
  location: class Main
1 error

Default methods

Adding a new abstract method to an interface breaks every class that implements it:

interface PaymentMethod {
    void pay(int amount);
    void receipt(int amount);
}
Main.java:5: error: Upi is not abstract and does not override abstract method receipt(int) in PaymentMethod
class Upi implements PaymentMethod {
^
Main.java:8: error: Card is not abstract and does not override abstract method receipt(int) in PaymentMethod
class Card implements PaymentMethod {
^
2 errors

A default method is an interface method with a body: every implementing class gets it for free, and any class may override it (write its own version). It's like a company introducing a uniform rule but handing out a standard uniform. A static interface method is a helper that belongs to the interface itself, called as PaymentMethod.isValid(...).

interface PaymentMethod {
    void pay(int amount);
    default void receipt(int amt) { System.out.println("  receipt Rs " + amt); }
    static boolean isValid(int amount) { return amount > 0; }
}
class Upi implements PaymentMethod {
    public void pay(int amount) { System.out.println("UPI: Rs " + amount); }
}
class Card implements PaymentMethod {
    public void pay(int amount) { System.out.println("Card: Rs " + amount); }
    public void receipt(int amt) { System.out.println("  card slip Rs " + amt); }
}
public class Main {
    static void checkout(PaymentMethod m, int amount) {
        if (!PaymentMethod.isValid(amount)) {
            System.out.println("Invalid amount: " + amount); return;
        }
        m.pay(amount);
        m.receipt(amount);
    }
    public static void main(String[] args) {
        checkout(new Upi(), 250);
        checkout(new Card(), 400);
        checkout(new Upi(), 0);
    }
}
UPI: Rs 250
  receipt Rs 250
Card: Rs 400
  card slip Rs 400
Invalid amount: 0

2. Abstract classes and abstract methods

Every payment stores its amount, and total = amount + fee. The total logic is shared; only the fee differs. Interfaces cannot hold per-object fields (any field in an interface is a constant). An abstract class is like a bare-shell flat: the builder finishes the walls and plumbing (shared fields and code), each owner must finish the interiors (abstract methods: declared with no body), and nobody can live in the bare shell (you cannot new it).

abstract class Payment {
    protected final int amount;
    Payment(int amount) { this.amount = amount; }
    abstract int fee();
    int total() { return amount + fee(); }
}
class UpiPayment extends Payment {
    UpiPayment(int amount) { super(amount); }
    int fee() { return 0; }
}
class CardPayment extends Payment {
    CardPayment(int amount) { super(amount); }
    int fee() { return amount * 2 / 100; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println("UPI total: " + new UpiPayment(500).total());
        System.out.println("Card total: " + new CardPayment(500).total());
    }
}
UPI total: 500
Card total: 510
  • extends means "build on top of that class and get everything it has" (inheritance, episode 8).
  • super(amount) calls the parent class's constructor; it must be the first line.
  • protected lets subclasses read amount.

Payment p = new Payment(500); gives:

Main.java:18: error: Payment is abstract; cannot be instantiated
        Payment p = new Payment(500);
                    ^
1 error

Interface vs abstract class

Interface Abstract class
Purpose A promise of what a class can do (a role) A half-built class with shared code and data
Per-object fields No (only constants) Yes
Constructors No Yes
How many per class A class can implement many A class can extend only one
Methods abstract, default, static, private abstract and normal methods
Use for PaymentMethod, Vehicle, Comparable A shared base like Payment

Design advice: start with an interface; add an abstract class only when several implementations really share code and state.

3. Enums

The problem: status as a String

String status = "OUT_FOR_DELIVERY";
status = "DELIVERD";
if (status.equals("DELIVERED")) System.out.println("Ask for a rating");
else System.out.println("Still waiting... status = " + status);
Still waiting... status = DELIVERD

The fix: an enum

An enum (short for enumeration) is a type with a fixed set of named values, like a dropdown instead of a free-text box.

enum Status { PLACED, COOKING, OUT_FOR_DELIVERY, DELIVERED }

public class Main {
    public static void main(String[] args) {
        Status status = Status.OUT_FOR_DELIVERY;
        status = Status.DELIVERD;
        if (status == Status.DELIVERED) System.out.println("Ask for a rating");
        else System.out.println("Still waiting... status = " + status);
    }
}
Main.java:6: error: cannot find symbol
        status = Status.DELIVERD;
                       ^
  symbol:   variable DELIVERD
  location: class Status
1 error

Fixed spelling prints Ask for a rating. Each enum value exists exactly once, so comparing with == is safe.

Enums with fields and methods

Enums are full classes: each value can carry data through a constructor (always private), and the enum can have methods. values() returns all values in declaration order.

enum Status {
    PLACED("Order placed", 40), COOKING("Being cooked", 25),
    OUT_FOR_DELIVERY("On the way", 10), DELIVERED("Delivered", 0);
    private final String label;
    private final int mins;
    Status(String label, int mins) {
        this.label = label;
        this.mins = mins;
    }
    String label() { return label; }
    int mins() { return mins; }
}
public class Main {
    public static void main(String[] args) {
        for (Status s : Status.values())
            System.out.println(s + ": " + s.label() + ", " + s.mins() + " min");
    }
}
PLACED: Order placed, 40 min
COOKING: Being cooked, 25 min
OUT_FOR_DELIVERY: On the way, 10 min
DELIVERED: Delivered, 0 min

Enums also work in switch, and the compiler checks you covered every value in a switch expression:

static String message(Status s) {
    return switch (s) {
        case PLACED -> "We got your order";
        case COOKING -> "The chef is on it";
        case OUT_FOR_DELIVERY -> "On the way";
        case DELIVERED -> "Enjoy your meal";
    };
}

message(Status.COOKING) returns The chef is on it. Converting text into an enum uses Status.valueOf("COOKING"); a wrong name throws IllegalArgumentException: No enum constant Status.DELIVERD.

EnumMap

A map stores key-value pairs, like a word and its meaning in a dictionary. An EnumMap is a map whose keys are enum values: it keeps them in the enum's order and is very fast (internally an array).

import java.util.*;

enum Status { PLACED, COOKING, OUT_FOR_DELIVERY, DELIVERED }

public class Main {
    public static void main(String[] args) {
        List<Status> orders = List.of(Status.DELIVERED, Status.COOKING,
                                      Status.PLACED, Status.COOKING);
        EnumMap<Status, Integer> count = new EnumMap<>(Status.class);
        for (Status s : orders)
            count.put(s, count.getOrDefault(s, 0) + 1);
        System.out.println(count);
    }
}
{PLACED=1, COOKING=2, DELIVERED=1}

getOrDefault(key, 0) returns the value for the key, or 0 if the key is not there yet. Status.class tells the map which enum it is for.

4. Records

The problem: a value class

class Location {
    final double lat, lng;
    Location(double lat, double lng) { this.lat = lat; this.lng = lng; }
}
// main:
Location shop = new Location(12.97, 77.59);
Location home = new Location(12.97, 77.59);
System.out.println(shop);
System.out.println(shop.equals(home));
Location@15db9742
false

(The number after @ is a hash code and differs from run to run.) By default toString shows the class name and hash code, and equals only asks "is it the very same object?". For a value, same data should mean equal. Writing equals, hashCode and toString by hand is boilerplate: repetitive code copied into every class.

The fix: a record

A record is a class made only to carry values, like an address label. One line gives you a constructor, final fields, getter methods named after the fields, and value-based equals, hashCode and toString.

record Location(double lat, double lng) { }

public class Main {
    public static void main(String[] args) {
        Location shop = new Location(12.97, 77.59);
        Location home = new Location(12.97, 77.59);
        System.out.println(shop);
        System.out.println(shop.equals(home));
        System.out.println(shop.lat());
    }
}
Location[lat=12.97, lng=77.59]
true
12.97

Records are immutable (they never change after creation) and cannot extend another class (they can implement interfaces).

The compact constructor

A compact constructor is written with just the record's name and no parameter list. It runs before the fields are assigned, so it is the place to validate:

record Money(int rupees) {
    Money {
        if (rupees < 0)
            throw new IllegalArgumentException("Negative money: " + rupees);
    }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(new Money(250));
        System.out.println(new Money(-40));
    }
}
Money[rupees=250]
Exception in thread "main" java.lang.IllegalArgumentException: Negative money: -40
    at Money.<init>(Main.java:4)
    at Main.main(Main.java:10)

throw stops the code right there and reports the problem as an exception. A negative Money can never exist.

5. Generics

The problem: a box of Object

Object is the parent of every class, so a box of Object can hold anything. Getting a specific type back needs a cast, (Integer) x, which means "trust me, this is an Integer". The compiler cannot check it.

class Box {
    private Object item;
    void put(Object item) { this.item = item; }
    Object get() { return item; }
}
public class Main {
    public static void main(String[] args) {
        Box orderIds = new Box();
        orderIds.put("Biryani");
        Integer id = (Integer) orderIds.get();
        System.out.println("Order id: " + id);
    }
}
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
    at Main.main(Main.java:10)

The fix: a type parameter

A generic class has a type parameter, written in angle brackets like <T>: a blank label slot on the box design. When you use the class you fill it in: Box<Integer>. The compiler then checks every put and get, and no cast is needed.

class Box<T> {
    private T item;
    void put(T item) { this.item = item; }
    T get() { return item; }
}
public class Main {
    public static void main(String[] args) {
        Box<Integer> orderIds = new Box<>();
        orderIds.put("Biryani");
        Integer id = orderIds.get();
        System.out.println("Order id: " + id);
    }
}
Main.java:9: error: incompatible types: String cannot be converted to Integer
        orderIds.put("Biryani");
                     ^

With orderIds.put(1042); it prints Order id: 1042. new Box<>() uses the diamond <>: Java fills in the type from the left side. Generic type arguments must be reference types: Box<Integer>, not Box<int>. Records can be generic too: record Pair<A, B>(A first, B second) { }.

Bounded types

<T extends Number> is a bounded type: T must be Number or a subclass (Integer, Double...). In return, the code can call Number methods like doubleValue() on every T.

import java.util.*;

class Stats<T extends Number> {
    private final List<T> values = new ArrayList<>();
    void add(T v) { values.add(v); }
    double average() {
        double total = 0;
        for (T v : values) total += v.doubleValue();
        return total / values.size();
    }
}
public class Main {
    public static void main(String[] args) {
        Stats<Integer> ratings = new Stats<>();
        ratings.add(4); ratings.add(5); ratings.add(3);
        System.out.println("Average rating: " + ratings.average());
        Stats<String> names = new Stats<>();
    }
}
Main.java:17: error: type argument String is not within bounds of type-variable T
        Stats<String> names = new Stats<>();
              ^
  where T is a type-variable:
    T extends Number declared in class Stats
...
2 errors

Without the last line: Average rating: 4.0.

Wildcards

Is a List<Integer> a List<Number>? No. A List<Number> must accept any Number, so if a List<Integer> counted as one, someone could add a Double to your integer list (a basket of mangoes is not a "basket that accepts any fruit").

static double sum(List<Number> xs) { ... }
// main:
List<Integer> tips = List.of(20, 30, 50);
System.out.println("Tips: " + sum(tips));
Main.java:11: error: incompatible types: List<Integer> cannot be converted to List<Number>

A wildcard ? means "some type". List<? extends Number> = "a list of some kind of Number": you can read Numbers from it safely, but not add to it.

static double sum(List<? extends Number> xs) {
    double total = 0;
    for (Number x : xs) total += x.doubleValue();
    return total;
}
Tips: 100.0

The opposite, List<? super Integer>, means "a list that can hold Integers" (Integer or any parent type): you can add Integers to it. Memory aid, PECS: Producer Extends, Consumer Super.

static void addTip(List<? super Integer> tips) { tips.add(10); }
// main:
List<Number> all = new ArrayList<>();
addTip(all);
System.out.println(all);   // [10]

Type erasure

List<String> dishes = new ArrayList<>();
List<Integer> prices = new ArrayList<>();
System.out.println(dishes.getClass().getName());
System.out.println(prices.getClass().getName());
System.out.println(dishes.getClass() == prices.getClass());
java.util.ArrayList
java.util.ArrayList
true

Type erasure: the compiler checks all the generic types, then erases them; at run time both are plain ArrayList. Like a warehouse checking every box label at the gate, then peeling the labels off before loading the truck. Consequences: you cannot write new T(), T.class, or instanceof List<String>, and generics cost nothing at run time.

The class diagram

«enum» Status                 «interface» PaymentMethod             «record» Location
PLACED, COOKING,              + pay(amount): void                    lat: double
OUT_FOR_DELIVERY, DELIVERED   + receipt(amt)   «default»             lng: double
                              + isValid(amt)   «static»
                                 ^          ^      (dashed, hollow triangle = implements)
                               Upi        Card (+ overrides receipt)

Labels in « » are stereotypes: they say what kind of thing a box is.

Common mistakes

Mistake Exact message Why Fix
Add an abstract method to an existing interface Upi is not abstract and does not override abstract method receipt(int) in PaymentMethod Every implementer must write it Make it a default method
Implementing method not public pay(int) in Upi cannot implement pay(int) in PaymentMethod ... attempting to assign weaker access privileges; was public Interface methods are public Mark it public
new on an abstract class Payment is abstract; cannot be instantiated It is unfinished new CardPayment(500)
Enum typo cannot find symbol ... variable DELIVERD Not one of the fixed values Use a real constant
Wrong text in valueOf IllegalArgumentException: No enum constant Status.DELIVERD No such constant Validate input first
Comparing value classes with equals without overriding false for equal data Default equals = same object Use a record (or override equals and hashCode)
Casting out of an Object box ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer A cast can't be checked Use generics
Wrong type into a generic incompatible types: String cannot be converted to Integer The type parameter is checked Put the right type
Type outside a bound type argument String is not within bounds of type-variable T T extends Number Use a Number type
List<Integer> passed as List<Number> incompatible types: List<Integer> cannot be converted to List<Number> Generics are not covariant List<? extends Number>

Mini project

Add to the app: a Wallet payment (with a balance), an enum PizzaSize with prices, a record Address that rejects an empty PIN code, and a generic Pair<A, B> record.

Solution
enum PizzaSize {
    SMALL(199), MEDIUM(349), LARGE(499);
    private final int price;
    PizzaSize(int price) { this.price = price; }
    int price() { return price; }
}
record Address(String line, String pin) {
    Address {
        if (pin == null || pin.isBlank()) throw new IllegalArgumentException("PIN code is required");
    }
}
record Pair<A, B>(A first, B second) { }

interface PaymentMethod { void pay(int amount); }
class Wallet implements PaymentMethod {
    private int balance;
    Wallet(int balance) { this.balance = balance; }
    public void pay(int amount) {
        if (amount > balance) { System.out.println("Wallet: insufficient balance"); return; }
        balance -= amount;
        System.out.println("Wallet: Rs " + amount + ", left Rs " + balance);
    }
}
public class Main {
    public static void main(String[] args) {
        for (PizzaSize s : PizzaSize.values()) System.out.println(s + " " + s.price());
        System.out.println(PizzaSize.valueOf("MEDIUM").ordinal());
        Pair<String, Integer> p = new Pair<>("Biryani", 250);
        System.out.println(p + " " + p.first() + " " + p.second());
        PaymentMethod w = new Wallet(300);
        w.pay(250); w.pay(100);
        System.out.println(new Address("12 MG Road", "560001"));
        new Address("12 MG Road", " ");
    }
}
SMALL 199
MEDIUM 349
LARGE 499
1
Pair[first=Biryani, second=250] Biryani 250
Wallet: Rs 250, left Rs 50
Wallet: insufficient balance
Address[line=12 MG Road, pin=560001]
Exception in thread "main" java.lang.IllegalArgumentException: PIN code is required
    at Address.<init>(Main.java:11)
    at Main.main(Main.java:35)

ordinal() is a value's position in the enum, starting at 0.

Practice

  1. Interface or abstract class: (a) "anything that can be sorted by price", (b) "every report shares a header and footer, only the body differs"?
Solution

(a) An interface (a role many unrelated classes can have). (b) An abstract class with the shared header/footer code and an abstract body() method.

  1. Why is == safe for enums but not for Strings?
Solution

Each enum constant is a single object, created once. Two equal Strings can be two different objects, so == (same object?) can be false; use equals.

  1. Two records new Money(250) and new Money(250). What do == and equals give?
Solution

== is false (two objects), equals is true (same values).

  1. Will List<Object> list = new ArrayList<String>(); compile?
Solution

No: incompatible types. Generic types are not covariant; List<? extends Object> would accept it (read-only).

Quick quiz

A pizza size can only be SMALL, MEDIUM or LARGE, and each size has its own price. Which tool fits best?

  • A String field
  • An enum with a price field
  • A generic Box
  • An abstract class
Answer

An enum with a price field. A fixed set of choices is an enum, and each value carries its own price through the enum constructor.

Interview questions

  1. Interface vs abstract class? Interface: a role, no state, many per class. Abstract class: shared state and code, one per class.
  2. Why were default methods added to Java? To let interfaces grow (add methods) without breaking every existing implementation.
  3. Why use an enum instead of int or String constants? Type safety (no invalid values), readable names, data and behaviour attached, works with switch and EnumMap.
  4. What does a record generate? A canonical constructor, private final fields, accessor methods, equals, hashCode and toString.
  5. What is type erasure, and one consequence? Generic types are removed after compile-time checks; so you can't do new T() or instanceof List<String>.
  6. Explain PECS. Producer extends (read from it), consumer super (write to it).

Glossary

Term Meaning, with an example
Interface A list of methods a class promises to provide. interface PaymentMethod
implements A class taking on an interface. class Upi implements PaymentMethod
Override Writing your own version of an inherited or default method
Default method An interface method with a body, inherited for free. default void receipt(...)
Static interface method A helper called on the interface name. PaymentMethod.isValid(0)
Abstract class A class with shared code and state that cannot be instantiated. abstract class Payment
Abstract method A method with no body that subclasses must write. abstract int fee();
extends Building a class on top of another one
super(...) Calling the parent class's constructor
Instantiate Create an object with new
Enum A type with a fixed set of named values. enum Status { PLACED, ... }
Enum constant One of the values. Status.COOKING
values() All constants of an enum, in order
valueOf(text) Converts text into the enum constant with that name
ordinal() A constant's position, from 0
Map Key-value pairs, like a dictionary
EnumMap A fast map with enum keys, kept in enum order
getOrDefault A map's value for a key, or a default if missing
Record A class that just carries values. record Location(double lat, double lng)
Immutable Never changes after creation
Compact constructor A record constructor without a parameter list, used to validate
throw Stops and reports a problem as an exception
IllegalArgumentException The standard exception for a bad argument
Hash code A number used to identify / group an object (episode 4)
Boilerplate Repetitive code copied into many places
Object (class) The parent of every Java class
Cast (Integer) x: telling the compiler to treat a value as a type; checked only at run time
ClassCastException Thrown when a cast is wrong at run time
Generics Classes and methods with type parameters
Type parameter The blank type in angle brackets. T in Box<T>
Type argument The type filled in. Integer in Box<Integer>
Diamond <> Lets Java infer the type argument. new Box<>()
Bounded type A type parameter with a limit. T extends Number
Wildcard ?: "some type". List<? extends Number>
PECS Producer Extends, Consumer Super
Type erasure Generic types are checked at compile time and removed at run time
Stereotype A label in a class diagram like «interface», «enum», «record»

Summary

  • Interfaces are promises; code against them so new types are new classes. Default methods let interfaces grow; static methods are helpers.
  • Abstract classes share code and state; you can't new them; abstract methods must be written by subclasses.
  • Enums replace magic strings with fixed, checked values that can carry data; EnumMap maps them fast and in order.
  • Records are immutable values with free equals, hashCode, toString; validate in the compact constructor.
  • Generics move type errors from run time to compile time; bounds limit T; wildcards make APIs flexible; erasure removes the types at run time.

Next episode: Java for LLD 3: collections, equality and ordering.