Skip to lesson

Design classes from requirements

Designing classes means reading a requirement in plain words and deciding which classes to write, what each one stores, what each one does, and how they are linked. A few simple questions turn almost any requirement into a clean first design.

From words to classes: nouns and verbs

Read the requirement and mark the nouns (things) and verbs (actions). Nouns become classes or fields, verbs become methods, and rules with numbers, like "at most 2 books", become checks and constants.

In "A member can borrow up to 2 books. A book has a title.", member and book become classes, title becomes a field, borrow becomes a method and "up to 2" becomes the constant MAX_BOOKS = 2.

Example 1 · Requirement to classes: a library rule

LibraryDesign.javaJava
class Book {    private final String title;    private boolean borrowed;
    Book(String title) {        this.title = title;    }
    String getTitle() {        return title;    }
    boolean isBorrowed() {        return borrowed;    }
    void markBorrowed() {        borrowed = true;    }}
class Member {    static final int MAX_BOOKS = 2;    private final String name;    private int count;
    Member(String name) {        this.name = name;    }
    void borrow(Book b) {        if (count == MAX_BOOKS || b.isBorrowed()) {            System.out.println(name + " cannot borrow " + b.getTitle());            return;        }        b.markBorrowed();        count++;        System.out.println(name + " borrowed " + b.getTitle());    }}
public class LibraryDesign {    public static void main(String[] args) {        Member diya = new Member("Diya");        Member arjun = new Member("Arjun");        Book b1 = new Book("Godan");        diya.borrow(b1);        diya.borrow(new Book("Gitanjali"));        diya.borrow(new Book("Train to Pakistan"));        arjun.borrow(b1);    }}
Output
Diya borrowed Godan
Diya borrowed Gitanjali
Diya cannot borrow Train to Pakistan
Arjun cannot borrow Godan

What this code does

  • Nouns member and book became classes; title is one value, so it is a field. The verb borrow became a method.
  • The rule "up to 2" became the constant MAX_BOOKS, checked inside borrow, where the count lives. Member asks the book to change itself with markBorrowed(); there is no open setter.

Not every noun is a class. A noun that is just one value, like a name, a price or a time, is a field. A noun with its own data and actions, like a seat that can be booked and has a price, is a class.

Who owns each method?

Cohesion is how closely the fields and methods inside one class belong together. A class with high cohesion does one clear job with its own data; low cohesion means unrelated jobs are mixed in one class.

Put a method in the class that has the data it needs. The seat knows its own price, so price() belongs in Seat; the booking knows its seats and discount, so the total belongs in Booking.

Java
class Seat {    private boolean booked;            // the seat owns this data...    private final int price;
    Seat(int price) {        this.price = price;    }
    int price() { return price; }      // ...so the methods that use it live here    void book() { booked = true; }}
// In Booking: ask the seat, do not reach into it// show.seats[i].booked = true;   becomes   seat.book();

If a method keeps reaching into another object's fields, like show.seats[i].booked = true, it is in the wrong class: ask the owner instead, seat.book(). Keeping each method with its data gives every class high cohesion.

Then decide what each object needs to be valid from the start. Those values go into the constructor, and fields that never change become final.

Find the bug

Ask the owner

Select the line that is wrong.

Seat has a rule for booking. Which line goes around it?

Round 1 of 2

Inheritance, composition or interface?

This is the design choice interviewers ask about most. Say the sentence that is truly correct about the two classes, then pick the tool that matches it.

Example 2 · is-a with shared code: an abstract class

SeatDesign.javaJava
abstract class Seat {    private final String id;
    Seat(String id) {        this.id = id;    }
    String label() {        return id + " (Rs. " + price() + ")";    }
    abstract int price();}
class RegularSeat extends Seat {    RegularSeat(String id) {        super(id);    }
    @Override    int price() {        return 200;    }}
class ReclinerSeat extends Seat {    ReclinerSeat(String id) {        super(id);    }
    @Override    int price() {        return 450;    }}
public class SeatDesign {    public static void main(String[] args) {        Seat[] row = { new RegularSeat("A1"), new ReclinerSeat("R1") };        for (Seat s : row) {            System.out.println(s.label());        }    }}
Output
A1 (Rs. 200)
R1 (Rs. 450)

What this code does

  • "A recliner seat is a seat" is true, and both share id and label(). That is the case for an abstract parent.
  • abstract int price() makes every new seat type state its price; label() is written once for all.

Example 3 · can-do across unrelated classes: an interface

RefundDesign.javaJava
interface Refundable {    int refund();}
class MovieBooking implements Refundable {    private final int paid;
    MovieBooking(int paid) {        this.paid = paid;    }
    @Override    public int refund() {        return paid * 80 / 100;    }}
class FoodOrder implements Refundable {    private final int paid;    private final boolean cooked;
    FoodOrder(int paid, boolean cooked) {        this.paid = paid;        this.cooked = cooked;    }
    @Override    public int refund() {        return cooked ? 0 : paid;    }}
public class RefundDesign {    public static void main(String[] args) {        Refundable[] cancelled = { new MovieBooking(500), new FoodOrder(300, false), new FoodOrder(250, true) };        int total = 0;        for (Refundable r : cancelled) {            total += r.refund();        }        System.out.println("Total refund: Rs. " + total);    }}
Output
Total refund: Rs. 700

What this code does

  • A movie booking is not a food order, and neither is a kind of the other, so they share no parent. They only share an ability.
  • The interface lets one loop treat both the same way: 400 + 300 + 0.

The four sentences and their tools:

  • is-a, with shared fields and code → abstract class and extends: a recliner seat is a seat.
  • has-a or part of → composition, a field: a show has a movie and seats.
  • can-do, shared by unrelated classes → interface: a booking and a food order can both be refunded.
  • Behaviour that varies or mixes → composition with an interface field: a booking has a discount rule.

Abstract class or interface? How to choose (opens in a new tab) has the full comparison.

When unsure, prefer composition. It can change at run time and does not lock you into one parent, since a class can extend only one class.

Avoid the class explosion

Tickets have 2 coach types (AC, Sleeper) and 3 concessions (none, student, senior). With inheritance only, every mix needs a subclass like StudentAcTicket: 6 classes, and 8 after one more concession. This is a class explosion.

Example 4 · Behaviour that varies: composition instead of a class explosion

ConcessionDesign.javaJava
interface Concession {    int apply(int fare);}
class Ticket {    private final String coach;    private final int fare;    private final Concession concession;
    Ticket(String coach, int fare, Concession concession) {        this.coach = coach;        this.fare = fare;        this.concession = concession;    }
    String describe() {        return coach + ": Rs. " + concession.apply(fare);    }}
public class ConcessionDesign {    public static void main(String[] args) {        Concession none = fare -> fare;        Concession student = fare -> fare * 75 / 100;        Concession senior = fare -> fare * 60 / 100;        System.out.println(new Ticket("AC", 1500, student).describe());        System.out.println(new Ticket("Sleeper", 500, senior).describe());        System.out.println(new Ticket("Sleeper", 500, none).describe());    }}
Output
AC: Rs. 1125
Sleeper: Rs. 300
Sleeper: Rs. 500

What this code does

  • One Ticket class works with any concession. No StudentAcTicket or SeniorSleeperTicket subclasses are needed.
  • Each lambda is a short way to write a Concession object. A new offer is one new line, and Ticket does not change.
  • describe() delegates the price rule to the concession it holds: concession.apply(fare).

With composition, Ticket has a fare and a Concession field. Each concession is written once, any ticket can use any concession, and a short lambda like fare -> fare * 75 / 100 can be the concession itself.

The same idea makes changes cheap. A new festival offer is one new Discount, with no change to Booking.

Predict the output

One class, many rules

Read the code and pick what it prints.

Two carts, same items, different discount rules.

interface Discount {
int apply(int amount);
}
class Cart {
private int total;
private final Discount discount;
Cart(Discount discount) {
this.discount = discount;
}
void add(int price) {
total += price;
}
int pay() {
return discount.apply(total);
}
}
public class CartRound {
public static void main(String[] args) {
Cart a = new Cart(amount -> amount - 100);
Cart b = new Cart(amount -> amount > 1000 ? amount / 2 : amount);
a.add(700);
a.add(500);
b.add(700);
b.add(500);
System.out.println(a.pay() + " " + b.pay());
}
}

Check your design

Coupling is how much one class depends on the inside details of another. Loose coupling means classes talk only through a few methods or an interface, so one can change without breaking the other.

Before writing code, test the plan with a few quick questions. Good classes have high cohesion and loose coupling: they talk through methods and interfaces, never by changing each other's fields.

Example 5 · Worked design: a movie ticket system

MovieBookingDemo.javaJava
interface Discount {    int apply(int amount);}
class Movie {    private final String title;
    Movie(String title) {        this.title = title;    }
    String getTitle() {        return title;    }}
abstract class Seat {    private final String id;    private boolean booked;
    Seat(String id) {        this.id = id;    }
    String getId() {        return id;    }
    boolean isBooked() {        return booked;    }
    void book() {        booked = true;    }
    abstract int price();}
class RegularSeat extends Seat {    RegularSeat(String id) {        super(id);    }
    @Override    int price() {        return 200;    }}
class ReclinerSeat extends Seat {    ReclinerSeat(String id) {        super(id);    }
    @Override    int price() {        return 450;    }}
class SeatNotAvailableException extends Exception {    SeatNotAvailableException(String id) {        super("Seat " + id + " is already booked");    }}
class Show {    private final Movie movie;    private final String time;    private final Seat[] seats;
    Show(Movie movie, String time, Seat[] seats) {        this.movie = movie;        this.time = time;        this.seats = seats;    }
    Seat find(String id) {        for (Seat s : seats) {            if (s.getId().equals(id)) {                return s;            }        }        return null;    }
    String describe() {        return movie.getTitle() + " at " + time;    }}
class Booking {    private final String customer;    private final Show show;    private final Discount discount;    private int total;
    Booking(String customer, Show show, Discount discount) {        this.customer = customer;        this.show = show;        this.discount = discount;    }
    void addSeat(String id) throws SeatNotAvailableException {        Seat s = show.find(id);        if (s.isBooked()) {            throw new SeatNotAvailableException(id);        }        s.book();        total += s.price();    }
    String summary() {        return customer + ": " + show.describe() + ", Rs. " + discount.apply(total);    }}
public class MovieBookingDemo {    public static void main(String[] args) {        Seat[] seats = { new RegularSeat("A1"), new RegularSeat("A2"), new ReclinerSeat("R1") };        Show show = new Show(new Movie("Mission Chandrayaan"), "7 PM", seats);        Booking kavya = new Booking("Kavya", show, amount -> amount * 90 / 100);        Booking rohan = new Booking("Rohan", show, amount -> amount);        try {            kavya.addSeat("A1");            kavya.addSeat("R1");            System.out.println(kavya.summary());            rohan.addSeat("A2");            rohan.addSeat("A1");        } catch (SeatNotAvailableException e) {            System.out.println("Error: " + e.getMessage());        }        System.out.println(rohan.summary());    }}
Output
Kavya: Mission Chandrayaan at 7 PM, Rs. 585
Error: Seat A1 is already booked
Rohan: Mission Chandrayaan at 7 PM, Rs. 200

What this code does

  • Requirement: "A show plays a movie at a time and has seats. A customer books seats; recliners cost more; a discount may apply; a seat cannot be booked twice."
  • Choices: Show has-a Movie and Seats (composition); ReclinerSeat is-a Seat (inheritance); Booking has-a Discount (interface, given as a lambda); double booking throws a custom exception.
  • Kavya pays (200 + 450) × 90% = 585. Rohan gets A2, then A1 fails because Kavya holds it, so he pays only for A2.

Four questions; a "no" points to the part to change:

  • Can you describe each class in one sentence without "and"?
  • Does every class change only its own fields? If not, move that code into the owner.
  • Can you add a new type (seat, payment, discount) without editing old classes?
  • Can every object start in a valid state? Check values in the constructor.

Next step

Check your understanding

12 quick questions