Skip to lesson

Design classes from a real problem

Good class design starts from the problem, not from code. Write the problem in short sentences, then pull out the nouns (they become classes or fields), the verbs (they become methods) and the links between nouns (they become IS-A or HAS-A).

Step 1: write the problem in short sentences

Before any class, write what the app must do in plain sentences, one fact per sentence. This is the food delivery app used in this lesson:

  • A restaurant has a name and a menu of dishes; each dish has a name and a price.
  • A customer orders one or more dishes from one restaurant; each order line has a dish and a quantity.
  • The customer pays by UPI or card (more ways may come later).
  • A delivery partner picks up only a paid order and delivers it to the customer's city. An order is placed, then paid, then delivered.
Short sentences make the nouns, verbs and links easy to see. A vague requirement gives a vague design.

Step 2: nouns → classes or fields, verbs → methods

Use the nouns-and-verbs trick from Why object-oriented programming? (opens in a new tab). A noun with its own data and behaviour becomes a class (Dish, Order); a noun that is one value (price, city) becomes a field.

Example 1 · A restaurant that owns its menu

MenuDemo.javaJava
class Dish {    private String name;    private int price;
    Dish(String name, int price) {        this.name = name;        this.price = price;    }
    String getName() { return name; }    int getPrice() { return price; }}
class Restaurant {    private String name;    private Dish[] menu = new Dish[10];    private int count;
    Restaurant(String name) { this.name = name; }
    void addDish(String dishName, int price) {        menu[count] = new Dish(dishName, price);        count++;    }
    void showMenu() {        System.out.println(name + " menu:");        for (int i = 0; i < count; i++) {            System.out.println("  " + menu[i].getName() + " - Rs. " + menu[i].getPrice());        }    }}
public class MenuDemo {    public static void main(String[] args) {        Restaurant r = new Restaurant("Udupi Grand");        r.addDish("Idli", 40);        r.addDish("Masala Dosa", 80);        r.addDish("Filter Coffee", 30);        r.showMenu();    }}
Output
Udupi Grand menu:
  Idli - Rs. 40
  Masala Dosa - Rs. 80
  Filter Coffee - Rs. 30

What this code does

  • "Dish", "name" and "price": the dish is a class, its name and price are fields. Name and price now always travel together.
  • addDish creates each Dish inside the restaurant: composition, as chosen in step 3.

A noun that is a list of other things (menu) becomes an array field, Dish[] menu; a noun with a fixed set of values (placed, paid, delivered) becomes an enum field. Each verb becomes a method on the class that owns the data it needs: order.addItem(...), partner.deliver(order).

Rules go with the data. "A quantity must be at least 1" belongs in Order.addItem, because the order holds its items.

Step 3: decide each relationship

For every pair of classes that meet, ask this module's questions in order: IS-A? Owns the part's life (composition)? Groups parts that live on their own (aggregation)? Just uses it (association)? Does a behaviour vary (an interface delegate)?

Example 2 · An order with its own items

OrderItemsDemo.javaJava
class Dish {    private String name;    private int price;
    Dish(String name, int price) {        this.name = name;        this.price = price;    }
    String getName() { return name; }    int getPrice() { return price; }}
class OrderItem {    private Dish dish;    private int qty;
    OrderItem(Dish dish, int qty) {        this.dish = dish;        this.qty = qty;    }
    int amount() { return dish.getPrice() * qty; }    String describe() { return qty + " x " + dish.getName() + " = Rs. " + amount(); }}
class Order {    private OrderItem[] items = new OrderItem[10];    private int count;
    void addItem(Dish dish, int qty) {        if (qty < 1) {            System.out.println("Quantity must be at least 1");            return;        }        items[count] = new OrderItem(dish, qty);        count++;    }
    int total() {        int sum = 0;        for (int i = 0; i < count; i++) {            sum = sum + items[i].amount();        }        return sum;    }
    void printBill() {        for (int i = 0; i < count; i++) {            System.out.println(items[i].describe());        }        System.out.println("Total: Rs. " + total());    }}
public class OrderItemsDemo {    public static void main(String[] args) {        Dish dosa = new Dish("Masala Dosa", 80);        Dish coffee = new Dish("Filter Coffee", 30);        Order o = new Order();        o.addItem(dosa, 2);        o.addItem(coffee, 0);        o.addItem(coffee, 2);        o.printBill();    }}
Output
Quantity must be at least 1
2 x Masala Dosa = Rs. 160
2 x Filter Coffee = Rs. 60
Total: Rs. 220

What this code does

  • Order creates its OrderItems (composition). Each item only points to a Dish it was given (association).
  • The rule "quantity at least 1" sits in addItem, the method that owns the items. Every caller gets the check for free.

For the food app:

  • Restaurant owns its Dishes → composition (addDish creates them).
  • Order owns its OrderItems → composition; each OrderItem uses a Dish → association.
  • Order uses a Customer and a Restaurant that live on their own → association.
  • Payment varies (UPI, card, more later) → a PaymentMethod interface and delegation.

Step 4: draw a class diagram

A class diagram is a picture of the classes in a program and the links between them (IS-A, association, aggregation, composition), often with how many objects are on each side.

Draw the whole design on one screen before coding. Check it: every class has a job, every link has a reason, and no extends fails the sentence test.

Class diagram of a food delivery app. A Customer places an Order. The Order owns its OrderItems (filled diamond), comes from a Restaurant that has a Dish[] menu, and pays through Payment, an interface. Filled diamond means owns; plain lines mean uses.
On paper, a plain line per link also works: Order OWNS OrderItem[], Order USES Customer. A filled diamond marks composition, a hollow one aggregation.

Step 5: code it, test it, avoid the classic mistakes

A god class is one huge class that holds most of a program's data and does most of its jobs, so every change touches it and its data easily gets out of step.

Code the smallest classes first (Dish, Customer), then the ones that use them, and test each step with a short main. The finished app below follows the diagram link by link.

Example 3 · The whole app working together

FoodAppDemo.javaJava
interface PaymentMethod {    boolean pay(int amount);}
class UpiPayment implements PaymentMethod {    private String upiId;
    UpiPayment(String upiId) { this.upiId = upiId; }
    public boolean pay(int amount) {        System.out.println("Paid Rs. " + amount + " by UPI from " + upiId);        return true;    }}
class CardPayment implements PaymentMethod {    private int limit;
    CardPayment(int limit) { this.limit = limit; }
    public boolean pay(int amount) {        if (amount > limit) {            System.out.println("Card declined for Rs. " + amount);            return false;        }        System.out.println("Paid Rs. " + amount + " by card");        return true;    }}
enum OrderStatus { PLACED, PAID, DELIVERED }
class Dish {    private String name;    private int price;
    Dish(String name, int price) {        this.name = name;        this.price = price;    }
    String getName() { return name; }    int getPrice() { return price; }}
class Restaurant {    private String name;    private Dish[] menu = new Dish[10];    private int count;
    Restaurant(String name) { this.name = name; }
    String getName() { return name; }
    void addDish(String dishName, int price) {        menu[count] = new Dish(dishName, price);        count++;    }
    Dish find(String dishName) {        for (int i = 0; i < count; i++) {            if (menu[i].getName().equals(dishName)) {                return menu[i];            }        }        return null;    }}
class Customer {    private String name;    private String city;
    Customer(String name, String city) {        this.name = name;        this.city = city;    }
    String getName() { return name; }    String getCity() { return city; }}
class OrderItem {    private Dish dish;    private int qty;
    OrderItem(Dish dish, int qty) {        this.dish = dish;        this.qty = qty;    }
    int amount() { return dish.getPrice() * qty; }}
class Order {    private Customer customer;    private Restaurant restaurant;    private OrderItem[] items = new OrderItem[10];    private int count;    private OrderStatus status = OrderStatus.PLACED;
    Order(Customer customer, Restaurant restaurant) {        this.customer = customer;        this.restaurant = restaurant;    }
    void addItem(String dishName, int qty) {        Dish dish = restaurant.find(dishName);        if (dish == null) {            System.out.println(restaurant.getName() + " has no " + dishName);            return;        }        if (qty < 1) {            System.out.println("Quantity must be at least 1");            return;        }        items[count] = new OrderItem(dish, qty);        count++;        System.out.println("Added " + qty + " x " + dishName);    }
    int total() {        int sum = 0;        for (int i = 0; i < count; i++) {            sum = sum + items[i].amount();        }        return sum;    }
    void pay(PaymentMethod method) {        if (method.pay(total())) {            status = OrderStatus.PAID;        }    }
    void markDelivered() { status = OrderStatus.DELIVERED; }
    OrderStatus getStatus() { return status; }    Customer getCustomer() { return customer; }    Restaurant getRestaurant() { return restaurant; }}
class DeliveryPartner {    private String name;
    DeliveryPartner(String name) { this.name = name; }
    void deliver(Order o) {        if (o.getStatus() != OrderStatus.PAID) {            System.out.println(name + ": order is " + o.getStatus() + ", cannot pick up");            return;        }        System.out.println(name + " picked up from " + o.getRestaurant().getName());        o.markDelivered();        Customer c = o.getCustomer();        System.out.println(name + " delivered to " + c.getName() + " in " + c.getCity());    }}
public class FoodAppDemo {    public static void main(String[] args) {        Restaurant udupi = new Restaurant("Udupi Grand");        udupi.addDish("Masala Dosa", 80);        udupi.addDish("Filter Coffee", 30);
        Order o = new Order(new Customer("Kavya", "Mysuru"), udupi);        o.addItem("Masala Dosa", 2);        o.addItem("Pizza", 1);        o.addItem("Filter Coffee", 2);
        DeliveryPartner ravi = new DeliveryPartner("Ravi");        ravi.deliver(o);        o.pay(new CardPayment(200));        o.pay(new UpiPayment("kavya@upi"));        ravi.deliver(o);        System.out.println("Status: " + o.getStatus());    }}
Output
Added 2 x Masala Dosa
Udupi Grand has no Pizza
Added 2 x Filter Coffee
Ravi: order is PLACED, cannot pick up
Card declined for Rs. 220
Paid Rs. 220 by UPI from kavya@upi
Ravi picked up from Udupi Grand
Ravi delivered to Kavya in Mysuru
Status: DELIVERED

What this code does

  • Every link from the diagram is here. Restaurant and Order create their own parts (composition); Order uses the Customer and Restaurant it is given (association); each OrderItem points to a menu Dish.
  • Payment is a delegate behind PaymentMethod. The card declines and UPI succeeds, yet Order never changes; a new wallet is just one new class.
  • The order's state is an OrderStatus enum. The partner reads it through getStatus(), so an unpaid order can never be picked up.

Three classic design mistakes: a god class like FoodApp holding everything in parallel arrays; inheritance for roles, such as DeliveryPartner extends Customer just because both have a name and phone; and public fields that let any class change any data.

If two classes share fields like name and phone, first try a small shared part (a Contact object) before reaching for extends.

Next step

Check your understanding

12 quick questions