Part 08 / Stage 2
Object-oriented Java
Goal: Design your own classes instead of only using built-in ones — fields, constructors, encapsulation, inheritance, interfaces, enums and records — and build a small bank account system with them. Time: ~10 hours · Level: comfortable with Stage 1 Java (variables, control flow, methods, and using
ArrayList/HashMapwithout writing your own classes)
What you will learn
- Classes and objects: how each object gets its own, independent state
- Constructors, overloading them, and
this - Encapsulation:
privatefields, access modifiers, and validating through methods instead of exposing fields - Static members (shared by the class) versus instance members (one copy per object)
- The
Objectclass, and overridingtoString,equalsandhashCode - Inheritance,
super, andprotected - Polymorphism: one call site, the real object decides which method runs
- Abstract classes: a shared shape with some methods left for subclasses to finish
- Interfaces and
defaultmethods: a contract, with some behaviour included - Enums with their own fields and methods, not just names
- Records as plain, immutable data classes
- Putting all of it together in one small bank account system
About Stage 1: every program you wrote in Stage 1 lived inside one
staticmethod. You wrotestaticbecause the course told you to, without a real explanation (Part 1). This part is where that silence ends:staticversus instance is section 4, and from here on you are the one deciding what a class looks like.
Topics in this part
Practice
Try each one yourself first. Then check the solution. Every exercise is one .java file with a public static void main(String[] args) method inside a top-level class; the solutions use a non-public top-level class (class Ex01 { ... }), so the filename does not need to match it (Part 1, Exercise 6's note) — the stage-wide convention from here on.
Exercise 1: Movie tickets
Scenario: A multiplex sells tickets, and every ticket must have a positive seat count and price.
What to do: Write a class Ticket(movieName, seatCount, pricePerSeat) with private final fields, a constructor that rejects a seatCount of 0 or less and a pricePerSeat of 0 or less (IllegalArgumentException), a method totalCost() (seatCount * pricePerSeat), accessor methods movieName() and seatCount(), and a toString() like the sample output.
Build two tickets, print both, print the first one's movie name and seat count through its accessors, then try one Ticket with seatCount = 0 and one with a negative price, printing each rejection.
Sample output:
Pathaan: 3 seat(s) @ ₹220.0 = ₹660.0
Jawan: 1 seat(s) @ ₹350.0 = ₹350.0
Pathaan seat count: 3
rejected: seatCount must be positive: 0
rejected: pricePerSeat must be positive: -50.0
💡 Hint: Validate both fields in the constructor before assigning anything, the same order Encapsulation.java validates deposit/withdraw.
Exercise 2: Store coupons, with a default discount
Scenario: A store's coupons normally need an explicit discount, but a "welcome" coupon should default to 5% without repeating that number everywhere.
What to do: Write a class Coupon(code, discountPercent) that upper-cases code, rejects a discountPercent outside (0, 100], and a second constructor Coupon(code) that chains to it with this(code, 5.0). Add applyTo(amount) (price after the discount, rounded to 2 decimals) and a static counter issued() of how many coupons were successfully built. Print two coupons (one with an explicit discount, one using the default), the discounted price of ₹2000 under each, the issued count, then try a discountPercent of 150.0 and print the issued count again to show the rejected one did not count.
Sample output:
DIWALI20 (20.0% off)
WELCOME (5.0% off)
₹2000 with DIWALI20: ₹1600.0
₹2000 with WELCOME: ₹1900.0
coupons issued: 2
rejected: discountPercent must be between 0 and 100: 150.0
coupons issued: 2 (the rejected one did not count)
💡 Hint: this(code, DEFAULT_DISCOUNT_PERCENT); must be the very first line of the one-argument constructor. Increment the static counter at the end of the two-argument constructor, after validation, so a rejected coupon never increments it.
Exercise 3: Students, equal by roll number
Scenario: A school's attendance system re-enters a student's name slightly differently each term, but the same roll number must always mean the same student.
What to do: Write PlainStudent(rollNumber, name) with no overrides at all, and a separate Student(rollNumber, name) that overrides toString() (Student[7, Kiran] style), equals(Object) (equal only by rollNumber) and hashCode() (from rollNumber). Build two PlainStudents with the same data and print whether they are .equals(). Build two Students with the same roll number but different names, print both, their .equals() result and whether their hash codes match. Put both plus one more, different, Student into a HashSet and print its size.
Sample output:
PlainStudent p1.equals(p2): false (same data, but Object.equals checks identity)
s1 = Student[7, Kiran]
s2 = Student[7, Kiran Patil]
s1.equals(s2): true (equal because the roll number matches)
s1.hashCode() == s2.hashCode(): true
classroom size: 2 (s1 and s2 count as one student)
💡 Hint: follow the same two-step shape as section 5's ObjectMethods.java: first if (!(o instanceof Student)) return false;, then a separate cast Student other = (Student) o; before comparing rollNumber.
Exercise 4: Payroll with an abstract Employee
Scenario: A company pays every employee a base salary plus a bonus, but the bonus rule is different for every role, and a new role must never ship without its own rule.
What to do: Write an abstract class Employee(name, baseSalary) with an abstract double bonus() and a finished totalPay() (baseSalary + bonus()) and toString() that calls bonus(). Write Developer(name, baseSalary, projectsShipped) (bonus: projectsShipped * 5000.0) and Manager(name, baseSalary, teamSize) (bonus: teamSize * 2000.0), both extending Employee. Write totalPayroll(List<Employee> employees) that sums totalPay() over the list. Build a team of two developers and one manager, print each, then the total payroll.
Sample output:
Asha: base ₹80000.0 + bonus ₹15000.0 = ₹95000.0
Ravi: base ₹110000.0 + bonus ₹12000.0 = ₹122000.0
Meera: base ₹75000.0 + bonus ₹5000.0 = ₹80000.0
total payroll: ₹297000.0
💡 Hint: totalPay() lives on Employee and calls bonus() on this — it never needs to know whether this is a Developer or a Manager; that is decided at run time, the same polymorphism as section 8's statementLine().
Exercise 5: Discounts through an interface
Scenario: A shop gives a flat 10% off most things, but electronics get a steeper 15% off.
What to do: Write an interface Discountable with an abstract price() and a default double discountedPrice() that returns 10% off, rounded to 2 decimals. Write Grocery(name, price) that implements Discountable and uses the default as-is, and Electronics(name, price) that overrides discountedPrice() with 15% off instead. Put one of each in a List<Discountable> and print each item with its discounted price.
Sample output:
Headphones (₹2000.0) -> ₹1700.0
Rice 5kg (₹450.0) -> ₹405.0
💡 Hint: Electronics still implements price() itself; only discountedPrice() is overridden. This is the same pattern as FixedDeposit overriding tdsAmount() while SavingsAccount keeps the interface's default, in section 9.
Exercise 6: Delivery slots as an enum
Scenario: An online grocery app offers three fixed delivery windows, each with its own fee.
What to do: Write an enum DeliverySlot with constants MORNING(50.0), AFTERNOON(30.0), EVENING(70.0), a fee() accessor, and a window() method that returns an exhaustive switch on this ("8 AM - 11 AM" for MORNING, "12 PM - 4 PM" for AFTERNOON, "5 PM - 9 PM" for EVENING). Write an Order(item, slot) class whose toString() uses both. Loop over DeliverySlot.values() printing each one's ordinal, fee and window; print one Order; then valueOf("MORNING"), and catch what valueOf("NIGHT") throws.
Sample output:
MORNING ordinal=0 fee=₹50.0 window=8 AM - 11 AM
AFTERNOON ordinal=1 fee=₹30.0 window=12 PM - 4 PM
EVENING ordinal=2 fee=₹70.0 window=5 PM - 9 PM
Grocery bag delivered 5 PM - 9 PM, fee ₹70.0
valueOf("MORNING") = MORNING
valueOf("NIGHT") -> No enum constant Ex06.DeliverySlot.NIGHT
💡 Hint: The exact exception message includes the enum's fully-qualified name as Java sees it (here Ex06.DeliverySlot, since the enum is nested inside the exercise's top-level class) — print the real e.getMessage() rather than typing the message out by hand, so this matches whatever you named your own outer class.
Exercise 7: Customer records, and a record that implements an interface
Scenario: An online store stores customers and invoices as plain, immutable data, and export invoices are zero-rated for tax while everything else charges GST. What to do:
- Write a record
Address(line1, city, pincode)with a compact constructor that rejects anypincodethat is not exactly 6 digits (IllegalArgumentException, usepincode.matches("\\d{6}")). - Write a record
Customer(name, address)— a record whose component is itself a record. - Write an interface
Billablewith an abstractamount()and adefault double tax()returning 18% ofamount(), rounded to 2 decimals. - Write records
StandardInvoice(invoiceId, amount)andExportInvoice(invoiceId, amount), both implementingBillable;ExportInvoiceoverridestax()to always return0.0. - In
main, build oneCustomer, and a secondCustomerwith an equal but separately-constructedAddress; print the first, whether they.equals(), and the city read throughcustomer.address().city(). Try building anAddresswith a 4-digit pincode and print the rejection. Finally put oneStandardInvoiceand oneExportInvoicein aList<Billable>and print each with itstax().
Sample output:
Customer[name=Asha Kulkarni, address=Address[line1=12 MG Road, city=Pune, pincode=411001]]
asha.equals(ashaAgain): true (equal field by field, including the nested Address)
asha.address().city(): Pune
rejected: pincode must be exactly 6 digits, got 4000
StandardInvoice[invoiceId=INV-1001, amount=5000.0] -> tax ₹900.0
ExportInvoice[invoiceId=INV-1002, amount=20000.0] -> tax ₹0.0
💡 Hint: A record's generated equals() compares every component, including nested ones, by calling their equals() in turn — Address's generated equals() is what actually makes step 5's comparison work. A record can implements an interface exactly like any other class; the compact constructor still runs before any interface method is ever reachable.
Show the solutions for Part 8 (7 files)
solutions/ex01.java
// Exercise 1: a Ticket class with encapsulation and a validating constructor
class Ex01 {
static class Ticket {
private final String movieName;
private final int seatCount;
private final double pricePerSeat;
Ticket(String movieName, int seatCount, double pricePerSeat) {
if (seatCount <= 0) throw new IllegalArgumentException("seatCount must be positive: " + seatCount);
if (pricePerSeat <= 0) throw new IllegalArgumentException("pricePerSeat must be positive: " + pricePerSeat);
this.movieName = movieName;
this.seatCount = seatCount;
this.pricePerSeat = pricePerSeat;
}
String movieName() { return movieName; }
int seatCount() { return seatCount; }
double totalCost() {
return seatCount * pricePerSeat;
}
@Override
public String toString() {
return movieName + ": " + seatCount + " seat(s) @ ₹" + pricePerSeat + " = ₹" + totalCost();
}
}
public static void main(String[] args) {
Ticket t1 = new Ticket("Pathaan", 3, 220.0);
Ticket t2 = new Ticket("Jawan", 1, 350.0);
System.out.println(t1);
System.out.println(t2);
System.out.println(t1.movieName() + " seat count: " + t1.seatCount());
try {
new Ticket("Dunki", 0, 200.0);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
try {
new Ticket("Dunki", 2, -50.0);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
}
}
solutions/ex02.java
// Exercise 2: constructor overloading, this(...) chaining, and a static counter
class Ex02 {
static class Coupon {
private static int issued = 0;
private static final double DEFAULT_DISCOUNT_PERCENT = 5.0;
private final String code;
private final double discountPercent;
Coupon(String code, double discountPercent) {
if (discountPercent <= 0 || discountPercent > 100) {
throw new IllegalArgumentException("discountPercent must be between 0 and 100: " + discountPercent);
}
this.code = code.toUpperCase();
this.discountPercent = discountPercent;
issued++;
}
Coupon(String code) {
this(code, DEFAULT_DISCOUNT_PERCENT); // chains to the two-argument constructor
}
double applyTo(double amount) {
return Math.round(amount * (1 - discountPercent / 100) * 100) / 100.0;
}
static int issued() { return issued; }
@Override
public String toString() {
return code + " (" + discountPercent + "% off)";
}
}
public static void main(String[] args) {
Coupon diwali = new Coupon("diwali20", 20.0);
Coupon welcome = new Coupon("welcome"); // uses the default discount
System.out.println(diwali);
System.out.println(welcome);
System.out.println("₹2000 with " + diwali.code + ": ₹" + diwali.applyTo(2000.0));
System.out.println("₹2000 with " + welcome.code + ": ₹" + welcome.applyTo(2000.0));
System.out.println("coupons issued: " + Coupon.issued());
try {
new Coupon("BAD", 150.0);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
System.out.println("coupons issued: " + Coupon.issued() + " (the rejected one did not count)");
}
}
solutions/ex03.java
// Exercise 3: overriding equals/hashCode/toString, and the default Object behaviour without them
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
class Ex03 {
static class PlainStudent { // no overrides: Object's identity-based defaults
final int rollNumber;
final String name;
PlainStudent(int rollNumber, String name) { this.rollNumber = rollNumber; this.name = name; }
}
static class Student {
private final int rollNumber; // two students are "equal" if the roll number matches
private final String name;
Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
@Override
public String toString() {
return "Student[" + rollNumber + ", " + name + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student other = (Student) o;
return rollNumber == other.rollNumber;
}
@Override
public int hashCode() {
return Objects.hash(rollNumber);
}
}
public static void main(String[] args) {
PlainStudent p1 = new PlainStudent(7, "Kiran");
PlainStudent p2 = new PlainStudent(7, "Kiran");
System.out.println("PlainStudent p1.equals(p2): " + p1.equals(p2) + " (same data, but Object.equals checks identity)");
Student s1 = new Student(7, "Kiran");
Student s2 = new Student(7, "Kiran Patil"); // same roll number, name typed differently at re-entry
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s1.equals(s2): " + s1.equals(s2) + " (equal because the roll number matches)");
System.out.println("s1.hashCode() == s2.hashCode(): " + (s1.hashCode() == s2.hashCode()));
Set<Student> classroom = new HashSet<>();
classroom.add(s1);
classroom.add(s2);
classroom.add(new Student(9, "Priya"));
System.out.println("classroom size: " + classroom.size() + " (s1 and s2 count as one student)");
}
}
solutions/ex04.java
// Exercise 4: an abstract Employee hierarchy, overridden methods, and polymorphic payroll
import java.util.List;
class Ex04 {
abstract static class Employee {
protected final String name;
protected final double baseSalary;
Employee(String name, double baseSalary) {
this.name = name;
this.baseSalary = baseSalary;
}
abstract double bonus();
double totalPay() { return baseSalary + bonus(); }
@Override
public String toString() {
return name + ": base ₹" + baseSalary + " + bonus ₹" + bonus() + " = ₹" + totalPay();
}
}
static class Developer extends Employee {
private final int projectsShipped;
Developer(String name, double baseSalary, int projectsShipped) {
super(name, baseSalary);
this.projectsShipped = projectsShipped;
}
@Override
double bonus() { return projectsShipped * 5000.0; }
}
static class Manager extends Employee {
private final int teamSize;
Manager(String name, double baseSalary, int teamSize) {
super(name, baseSalary);
this.teamSize = teamSize;
}
@Override
double bonus() { return teamSize * 2000.0; }
}
static double totalPayroll(List<Employee> employees) {
double total = 0.0;
for (Employee e : employees) {
total += e.totalPay(); // dynamic dispatch: each employee's own bonus() runs
}
return total;
}
public static void main(String[] args) {
List<Employee> team = List.of(
new Developer("Asha", 80000.0, 3),
new Manager("Ravi", 110000.0, 6),
new Developer("Meera", 75000.0, 1)
);
for (Employee e : team) {
System.out.println(e);
}
System.out.println("total payroll: ₹" + totalPayroll(team));
}
}
solutions/ex05.java
// Exercise 5: an interface with a default method, implemented and overridden
import java.util.List;
class Ex05 {
interface Discountable {
double price();
default double discountedPrice() { // default: a flat 10% off
return Math.round(price() * 0.90 * 100) / 100.0;
}
}
static class Electronics implements Discountable {
private final String name;
private final double price;
Electronics(String name, double price) { this.name = name; this.price = price; }
@Override public double price() { return price; }
@Override
public double discountedPrice() { // electronics: a steeper 15% off
return Math.round(price() * 0.85 * 100) / 100.0;
}
@Override public String toString() { return name + " (₹" + price + ")"; }
}
static class Grocery implements Discountable {
private final String name;
private final double price;
Grocery(String name, double price) { this.name = name; this.price = price; }
@Override public double price() { return price; } // uses the default discountedPrice()
@Override public String toString() { return name + " (₹" + price + ")"; }
}
public static void main(String[] args) {
List<Discountable> items = List.of(
new Electronics("Headphones", 2000.0),
new Grocery("Rice 5kg", 450.0)
);
for (Discountable item : items) {
System.out.println(item + " -> ₹" + item.discountedPrice());
}
}
}
solutions/ex06.java
// Exercise 6: an enum with fields, a method, and an exhaustive switch
class Ex06 {
enum DeliverySlot {
MORNING(50.0), AFTERNOON(30.0), EVENING(70.0);
private final double feeRupees;
DeliverySlot(double feeRupees) { this.feeRupees = feeRupees; }
double fee() { return feeRupees; }
String window() {
return switch (this) {
case MORNING -> "8 AM - 11 AM";
case AFTERNOON -> "12 PM - 4 PM";
case EVENING -> "5 PM - 9 PM";
};
}
}
static class Order {
private final String item;
private final DeliverySlot slot;
Order(String item, DeliverySlot slot) {
this.item = item;
this.slot = slot;
}
@Override
public String toString() {
return item + " delivered " + slot.window() + ", fee ₹" + slot.fee();
}
}
public static void main(String[] args) {
for (DeliverySlot slot : DeliverySlot.values()) {
System.out.printf("%-10s ordinal=%d fee=₹%.1f window=%s%n", slot, slot.ordinal(), slot.fee(), slot.window());
}
Order order = new Order("Grocery bag", DeliverySlot.EVENING);
System.out.println(order);
DeliverySlot parsed = DeliverySlot.valueOf("MORNING");
System.out.println("valueOf(\"MORNING\") = " + parsed);
try {
DeliverySlot.valueOf("NIGHT");
} catch (IllegalArgumentException e) {
System.out.println("valueOf(\"NIGHT\") -> " + e.getMessage());
}
}
}
solutions/ex07.java
// Exercise 7: records composing records, and a record implementing an interface with a default method
import java.util.List;
class Ex07 {
record Address(String line1, String city, String pincode) {
Address { // compact constructor: validate before fields are set
if (pincode == null || !pincode.matches("\\d{6}")) {
throw new IllegalArgumentException("pincode must be exactly 6 digits, got " + pincode);
}
}
}
record Customer(String name, Address address) {} // a record composed of another record
interface Billable {
double amount();
default double tax() { // default: a flat 18% GST
return Math.round(amount() * 0.18 * 100) / 100.0;
}
}
record StandardInvoice(String invoiceId, double amount) implements Billable {}
record ExportInvoice(String invoiceId, double amount) implements Billable {
@Override
public double tax() { return 0.0; } // exports are zero-rated: overrides the default
}
public static void main(String[] args) {
Address puneAddress = new Address("12 MG Road", "Pune", "411001");
Customer asha = new Customer("Asha Kulkarni", puneAddress);
Customer ashaAgain = new Customer("Asha Kulkarni", new Address("12 MG Road", "Pune", "411001"));
System.out.println(asha);
System.out.println("asha.equals(ashaAgain): " + asha.equals(ashaAgain) + " (equal field by field, including the nested Address)");
System.out.println("asha.address().city(): " + asha.address().city());
try {
new Address("Flat 4B", "Mumbai", "4000");
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
List<Billable> invoices = List.of(
new StandardInvoice("INV-1001", 5000.0),
new ExportInvoice("INV-1002", 20000.0)
);
for (Billable invoice : invoices) {
System.out.println(invoice + " -> tax ₹" + invoice.tax());
}
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Public fields with no constructor validation | Nothing stops acc.balance = -999999; from outside the class |
Make fields private, change them only through methods that check |
this.owner = owner; written as owner = owner; |
Assigns the parameter to itself; the field never gets set | Always write this.field = parameter; when names collide |
Overriding equals without hashCode |
Collections may never find an object that is "equal" by your own rule | Override both, from the same fields |
public boolean equals(BankAccount other) |
A different parameter type overloads, it does not override Object.equals(Object) — collections never call it |
Always write equals(Object o), and use @Override so the compiler catches the mismatch |
A plain superclass method that just returns a safe-looking default (e.g. monthlyFee() { return 0.0; }) |
Easy to forget to override in a new subclass; the bug is silent | Make the method abstract when every subclass must genuinely decide its own value |
Calling super(...) after other statements, or not at all when the superclass has no no-argument constructor |
super(...) must be the first statement; the compiler rejects anything else |
Put super(...) on the very first line of the subclass constructor |
| Reaching for inheritance because two classes share a little code | Produces a fragile hierarchy for an "IS-A" relationship that is not really true | Ask whether the subclass genuinely is a kind of the superclass; otherwise give the class a field that holds the other object instead of extending it |
Mutable fields on a record component, or giving a record a setter |
Defeats the reason to use a record at all: records are supposed to be immutable data | Use a regular class once the object needs to change after construction |
static fields that many objects write to, "to share state" |
Hidden shared mutable state, hard to trace, and dangerous once threads exist (Stage 3) | Make the value static only if it is a true constant or counter; otherwise keep it per-instance |
Quick recap
- A class is a blueprint; each object built with
newgets its own independent copy of the instance fields. - Constructors validate and set up an object once, at creation;
thisrefers to the current object and resolves name clashes with parameters;this(...)chains to another constructor. - Encapsulation means
privatefields changed only through methods that can enforce rules;protectedopens a field to subclasses,publicopens it to everyone. staticmembers belong to the class, shared by every object; instance members belong to one object each.- Every class extends
Object; overridetoString,equals(withObjectas the parameter type) andhashCodetogether to get printing and value-equality that behave the way you intend. extendsreuses a superclass's fields and methods;super(...)must run first in a subclass constructor;super.method()reuses the overridden method's own logic.- Polymorphism means the object's real, run-time type decides which overridden method runs, even through a superclass-typed variable or list.
abstractclasses can leave specific methods unfinished on purpose, enforced by the compiler;interfaces are pure contracts, optionally withdefaultmethod bodies, and a class can implement several.- Enums are real classes with a fixed set of instances, each able to carry its own fields and share methods.
- Records are plain, immutable data: fields, accessors,
equals/hashCode/toStringgenerated from the component list, with a compact constructor for validation.
Checklist
- I wrote a class with its own fields and built more than one independent object from it.
- I wrote a constructor that validates its input and rejects bad data with an exception.
- I used
thisto resolve a parameter/field name clash, and chained one constructor to another withthis(...). - I made fields
privateand only changed them through checked methods. - I can say, for any field or method, whether it should be
staticor per-instance, and why. - I overrode
toString,equalsandhashCodetogether on a class, and saw aHashSettreat two "equal" objects as one. - I wrote a subclass with
extends, calledsuper(...)from its constructor, and overrode a method withsuper.method()inside it. - I put different subclasses in one
Listof their shared supertype and called an overridden method polymorphically. - I wrote an abstract class with at least one abstract method, and watched
javacrefuse to instantiate it directly. - I wrote an interface with a
defaultmethod, implemented it in two classes, and overrode the default in one of them. - I wrote an enum with fields set through its own constructor, plus at least one method that uses
this. - I wrote a record with a compact constructor that validates its components, and compared two instances with
equals. - I built the bank account system in section 12 (or my own equivalent) and traced which piece of the code each line of output came from.