Build a multi-class application
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A multi-class application is a program where several small classes each do one job and work together through method calls. Building one step by step, and running it after every step, is how real projects grow without getting lost.
The plan: a campus canteen app
Requirement: "The canteen menu has snacks and meals; meals add a Rs. 10 plate charge. A student pays from a prepaid wallet. An order holds several items. Orders of Rs. 100 or more get Rs. 10 off, and the offer may change. If the wallet is short, the payment fails with a clear message."
Using the noun-verb method (opens in a new tab) and the relationship tests gives this plan. Write it down, or draw it as below, before any code: it is your map.
MenuItem(abstract) withSnackandMeal: is-a, shared name and price.Studenthas-aWallet;OrderhasMenuItems;Canteenhas a menu and anOfferRule.OfferRuleinterface: the offer may change, so it is a lambda passed in.InsufficientBalanceException: a custom checked exception for a short wallet.
Build in layers and run after each step
Do not type all eight classes and then press Run: errors from many classes at once are hard to untangle. Build from the bottom up, first the classes that need nothing else, and run a small main after each step.
Example 1 · Step 1: the menu model
abstract class MenuItem { private final String name; private final int basePrice;
MenuItem(String name, int basePrice) { if (basePrice <= 0) { throw new IllegalArgumentException("Price must be positive: " + name); } this.name = name; this.basePrice = basePrice; }
String getName() { return name; }
int getBasePrice() { return basePrice; }
abstract int price();
@Override public String toString() { return name + " - Rs. " + price(); }}
class Snack extends MenuItem { Snack(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice(); }}
class Meal extends MenuItem { static final int PLATE_CHARGE = 10;
Meal(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice() + PLATE_CHARGE; }}
public class MenuStep { public static void main(String[] args) { MenuItem[] menu = { new Snack("Samosa", 15), new Snack("Chai", 10), new Meal("Veg Thali", 80) }; for (MenuItem item : menu) { System.out.println(item); } try { new Snack("Free Lunch", 0); } catch (IllegalArgumentException e) { System.out.println("Rejected: " + e.getMessage()); } }}Samosa - Rs. 15 Chai - Rs. 10 Veg Thali - Rs. 90 Rejected: Price must be positive: Free Lunch
What this code does
MenuItemholds what every item shares and forces each type to defineprice().Mealadds the plate charge from a named constant.- The constructor rejects a bad price, so no invalid item can exist.
toString()letsprintln(item)print a menu line.
Example 2 · Step 2: the wallet and a custom exception
class InsufficientBalanceException extends Exception { InsufficientBalanceException(int needed, int balance) { super("Need Rs. " + needed + ", wallet has Rs. " + balance); }}
class Wallet { private int balance;
Wallet(int balance) { this.balance = balance; }
int getBalance() { return balance; }
void pay(int amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException(amount, balance); } balance -= amount; }}
public class WalletStep { public static void main(String[] args) { Wallet w = new Wallet(100); try { w.pay(60); System.out.println("Paid 60, left Rs. " + w.getBalance()); w.pay(60); System.out.println("Paid 60 again"); } catch (InsufficientBalanceException e) { System.out.println("Failed: " + e.getMessage()); } System.out.println("Final balance: Rs. " + w.getBalance()); }}Paid 60, left Rs. 40 Failed: Need Rs. 60, wallet has Rs. 40 Final balance: Rs. 40
What this code does
paydeclaresthrows InsufficientBalanceException, so javac forces every caller to handle it.- When the payment fails, the balance is not changed: the check happens before
balance -= amount.
Example 3 · Step 3: the order and the offer rule
abstract class MenuItem { private final String name; private final int basePrice;
MenuItem(String name, int basePrice) { this.name = name; this.basePrice = basePrice; }
int getBasePrice() { return basePrice; }
abstract int price();}
class Snack extends MenuItem { Snack(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice(); }}
interface OfferRule { int apply(int total);}
class Order { private final MenuItem[] items = new MenuItem[5]; private int count;
void add(MenuItem item) { items[count] = item; count++; }
int total() { int sum = 0; for (int i = 0; i < count; i++) { sum += items[i].price(); } return sum; }}
public class OrderStep { public static void main(String[] args) { Order o = new Order(); o.add(new Snack("Vada Pav", 25)); o.add(new Snack("Cold Coffee", 85)); OfferRule tenOffAbove100 = total -> total >= 100 ? total - 10 : total; OfferRule noOffer = total -> total; System.out.println("Total: Rs. " + o.total()); System.out.println("With offer: Rs. " + tenOffAbove100.apply(o.total())); System.out.println("Without offer: Rs. " + noOffer.apply(o.total())); }}Total: Rs. 110 With offer: Rs. 100 Without offer: Rs. 110
What this code does
Orderhas an array of items (composition) and asks each one for itsprice()(polymorphism).OfferRulehas one method, so a lambda can be the rule. Changing the offer never touchesOrder.- Only the parts of
MenuItemthis step needs are included, to keep the test small.
The whole build has five steps; the first three are above, and the last two follow in the next section:
- Model:
MenuItem,Snack,Meal. Print the menu. - Money:
WalletandInsufficientBalanceException. Test a payment that works and one that fails. - Order:
OrderandOfferRule. Check totals with and without the offer. - App:
Student,Canteenandmain. Run one full flow. - Extend: add a new item type without editing old classes.
main that tests one step is often called a driver. Delete it or move it once the next step uses the class.Where each OOP idea fits
The finished app uses every big OOP idea, each for a clear reason. Step 4 joins the parts into one flow, and step 5 adds a new item type without touching the old classes.
Example 4 · Step 4: the complete app
abstract class MenuItem { private final String name; private final int basePrice;
MenuItem(String name, int basePrice) { if (basePrice <= 0) { throw new IllegalArgumentException("Price must be positive: " + name); } this.name = name; this.basePrice = basePrice; }
String getName() { return name; }
int getBasePrice() { return basePrice; }
abstract int price();
@Override public String toString() { return name + " - Rs. " + price(); }}
class Snack extends MenuItem { Snack(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice(); }}
class Meal extends MenuItem { static final int PLATE_CHARGE = 10;
Meal(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice() + PLATE_CHARGE; }}
class InsufficientBalanceException extends Exception { InsufficientBalanceException(int needed, int balance) { super("Need Rs. " + needed + ", wallet has Rs. " + balance); }}
class Wallet { private int balance;
Wallet(int balance) { this.balance = balance; }
int getBalance() { return balance; }
void pay(int amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException(amount, balance); } balance -= amount; }}
interface OfferRule { int apply(int total);}
class Order { private final MenuItem[] items = new MenuItem[5]; private int count;
void add(MenuItem item) { items[count] = item; count++; }
int total() { int sum = 0; for (int i = 0; i < count; i++) { sum += items[i].price(); } return sum; }}
class Student { private final String name; private final Wallet wallet;
Student(String name, Wallet wallet) { this.name = name; this.wallet = wallet; }
String getName() { return name; }
Wallet getWallet() { return wallet; }}
class Canteen { private final MenuItem[] menu; private final OfferRule offer;
Canteen(MenuItem[] menu, OfferRule offer) { this.menu = menu; this.offer = offer; }
void showMenu() { System.out.println("--- Menu ---"); for (MenuItem item : menu) { System.out.println(item); } }
void checkout(Student s, Order o) { int amount = offer.apply(o.total()); try { s.getWallet().pay(amount); System.out.println(s.getName() + " paid Rs. " + amount + ", balance Rs. " + s.getWallet().getBalance()); } catch (InsufficientBalanceException e) { System.out.println(s.getName() + ": payment failed. " + e.getMessage()); } }}
public class CanteenApp { public static void main(String[] args) { MenuItem samosa = new Snack("Samosa", 15); MenuItem chai = new Snack("Chai", 10); MenuItem thali = new Meal("Veg Thali", 80); Canteen canteen = new Canteen(new MenuItem[] { samosa, chai, thali }, total -> total >= 100 ? total - 10 : total); canteen.showMenu();
Student aarav = new Student("Aarav", new Wallet(150)); Order o1 = new Order(); o1.add(thali); o1.add(chai); o1.add(samosa); canteen.checkout(aarav, o1);
Student diya = new Student("Diya", new Wallet(50)); Order o2 = new Order(); o2.add(thali); canteen.checkout(diya, o2); }}--- Menu --- Samosa - Rs. 15 Chai - Rs. 10 Veg Thali - Rs. 90 Aarav paid Rs. 105, balance Rs. 45 Diya: payment failed. Need Rs. 90, wallet has Rs. 50
What this code does
- Flow:
mainbuilds the menu and canteen, then eachcheckouttotals the order, applies the offer and asks the wallet to pay. - Aarav: 90 + 10 + 15 = 115, which is 100 or more, so Rs. 10 off: 105. Diya's thali costs 90, but she has only 50.
Canteencatches the exception and prints a friendly message; the program keeps running.
Example 5 · Step 5: extend without editing: a combo item
abstract class MenuItem { private final String name; private final int basePrice;
MenuItem(String name, int basePrice) { this.name = name; this.basePrice = basePrice; }
String getName() { return name; }
int getBasePrice() { return basePrice; }
abstract int price();}
class Snack extends MenuItem { Snack(String name, int basePrice) { super(name, basePrice); }
@Override int price() { return getBasePrice(); }}
class Combo extends MenuItem { private final MenuItem[] parts; private final int saving;
Combo(String name, MenuItem[] parts, int saving) { super(name, 1); this.parts = parts; this.saving = saving; }
@Override int price() { int sum = 0; for (MenuItem p : parts) { sum += p.price(); } return sum - saving; }}
public class ComboStep { public static void main(String[] args) { MenuItem samosa = new Snack("Samosa", 15); MenuItem chai = new Snack("Chai", 10); MenuItem combo = new Combo("Samosa + Chai", new MenuItem[] { samosa, samosa, chai }, 5); MenuItem[] menu = { samosa, chai, combo }; for (MenuItem m : menu) { System.out.println(m.getName() + ": Rs. " + m.price()); } }}Samosa: Rs. 15 Chai: Rs. 10 Samosa + Chai: Rs. 35
What this code does
Combois-aMenuItemand has otherMenuItems. Its price is the sum of its parts minus a saving: 15 + 15 + 10 - 5.- Nothing else changes:
OrderandCanteenalready work with anyMenuItem. This is open/closed in practice. - The
super(name, 1)passes a placeholder base price, because a combo works out its price from its parts.
Each idea has its job:
- Encapsulation:
Wallet.balanceis private; money moves only throughpay, which checks the amount. - Inheritance and polymorphism:
Order.total()addsitem.price(); each item type decides its own price. - Abstraction:
Canteenknows only theOfferRuleinterface, not which offer it is. - Composition: a student has a wallet, an order has items, the canteen has a menu and an offer.
Find the bug
Which idea is broken?
Select the line that is wrong.
Which line lets any class skip the balance check?
Round 1 of 3Exception) because a short wallet is a normal situation the caller must plan for. Bad input like a price of 0 is a programming mistake, so it uses the unchecked IllegalArgumentException.Catch errors at the right level
Wallet.pay throws the exception but does not catch it. The wallet cannot know what the app should do: show a message, ask for a top-up, or cancel the order. It only reports the problem.
// In Wallet: the problem is found here, so throwvoid pay(int amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException(amount, balance); } balance = balance - amount;}
// In Canteen.checkout: the app decides what the student sees, so catch// try {// s.getWallet().pay(amount);// } catch (InsufficientBalanceException e) {// System.out.println(s.getName() + ": payment failed. " + e.getMessage());// }Canteen.checkout catches it, because that is where the app decides what the student sees. A good rule: throw where the problem is found, and catch where you know how to respond.
Order of execution
When the wallet is short
Diya has Rs. 50 and orders a Veg Thali (Rs. 90). Tap the steps of canteen.checkout(diya, o2) in order.
Splitting the app into packages
This lesson keeps the app in one file so you can run it at once. In a real project, each top-level class goes in its own file, and related classes are grouped into packages (folders), as you saw in Basics.
// file canteen/payment/Wallet.javapackage canteen.payment;
public class Wallet { // public: other packages use it private int balance; public Wallet(int balance) { this.balance = balance; } public int getBalance() { return balance; }}
// file canteen/app/CanteenApp.javapackage canteen.app;
import canteen.payment.Wallet;Across packages, a class can use only public classes, constructors and methods (a subclass can also use protected ones). So when you split the app, mark what other packages call as public, and keep the rest package-private or private. Each file starts with its package line and the imports it needs.
canteen.model:MenuItem.java,Snack.java,Meal.java,Student.java.canteen.payment:Wallet.java,InsufficientBalanceException.java.canteen.order:Order.java,OfferRule.java,Canteen.java.canteen.app:CanteenApp.javawithmain.
Fix the error
Wiring errors
Read the error, then pick the line that fixes it.
Round 1 of 2
CanteenApp is in another package and needs a Wallet.
Error
canteen/app/CanteenApp.java:3: error: Wallet is not public in canteen.payment; cannot be accessed from outside package
import canteen.payment.Wallet;
^Next step
Check your understanding
12 quick questions