Skip to lesson

Read an unfamiliar OOP program

Reading an OOP program means building a picture in your head: which objects exist, how they are linked, and which method calls which. A fixed routine makes any program readable, even one with ten classes you have never seen.

Read in running order

Code tracing is running a program by hand, line by line, in the order Java runs it, while writing down every variable, object and printed line, so you can predict exactly what the program does.

An exam question gives you 40 lines and four classes and asks what prints. Reading from the first line to the last fails: classes are only blueprints, and nothing in them runs until some code creates an object or calls a method.

Example 1 · Start at main, not at the top

ReadDemo.javaJava
class Printer {    void print(Student s) {        System.out.println(s.name + ": " + s.marks);    }}
class Student {    String name;    int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }}
public class ReadDemo {    public static void main(String[] args) {        Printer p = new Printer();        Student s = new Student("Kavya", 91);        p.print(s);        s.marks = 95;        p.print(s);    }}
Output
Kavya: 91
Kavya: 95

What this code does

  • Printer comes first in the file, but nothing runs until main creates objects and calls print.
  • print receives a reference to the same student, so the second call sees the new marks.

So read in the order Java runs it, with the same five steps every time, for a 30-line exam question or a 30-class project:

  1. Find main, the entry point: the method where running starts.
  2. List the classes: for each one, its fields, constructors and methods.
  3. Mark the links: extends, implements, fields of another class type.
  4. Walk through main line by line. Number each object as new creates it: #1, #2.
  5. For each call, jump to the method that really runs, finish it, then come back.
In an IDE, Ctrl+click (Cmd+click on macOS) on a method name jumps to its code. It is the fastest way to follow a call.

Map the classes and their links

Before tracing, spend one minute on a map. Fields say what an object knows, constructors what it needs to be created, and methods what it does. Then mark how the classes are linked.

Map of the food order program: main, the entry point, creates an Order. Order has a Customer field, has an Item[] array field and uses a Payment parameter. UpiPayment is a Payment.

Example 2 · Worked example: a five-class food order

FoodOrderDemo.javaJava
class Item {    String name;    int price;
    Item(String name, int price) {        this.name = name;        this.price = price;    }}
class Customer {    String name;
    Customer(String name) {        this.name = name;    }}
abstract class Payment {    abstract String pay(int amount);}
class UpiPayment extends Payment {    String upiId;
    UpiPayment(String upiId) {        this.upiId = upiId;    }
    @Override    String pay(int amount) {        return "Paid Rs. " + amount + " by UPI (" + upiId + ")";    }}
class Order {    Customer customer;    Item[] items = new Item[5];    int count;
    Order(Customer customer) {        this.customer = customer;    }
    void add(Item item) {        items[count] = item;        count++;    }
    int total() {        int sum = 0;        for (int i = 0; i < count; i++) {            sum += items[i].price;        }        return sum;    }
    void checkout(Payment payment) {        System.out.println(customer.name + " ordered " + count + " items");        System.out.println(payment.pay(total()));    }}
public class FoodOrderDemo {    public static void main(String[] args) {        Customer priya = new Customer("Priya");        Order order = new Order(priya);        order.add(new Item("Masala Dosa", 90));        order.add(new Item("Filter Coffee", 40));        order.checkout(new UpiPayment("priya@okbank"));    }}
Output
Priya ordered 2 items
Paid Rs. 130 by UPI (priya@okbank)

What this code does

  • Map: UpiPayment is-a Payment; Order has-a Customer and has Items; checkout uses a Payment.
  • Trace: priya → #1, order → #2 (customer = #1), two items #3 and #4 go into the array, then checkout runs.
  • In payment.pay(total()), total() returns 130 first; pay runs the UpiPayment version because the object is a UpiPayment.

These four links cover almost every program you will meet:

  • class UpiPayment extends Payment → is-a: a UPI payment is a payment.
  • class Duck implements Flyable → can-do: a duck can fly.
  • Customer customer; as a field → has-a: an order has a customer.
  • void checkout(Payment p) → uses: the order only uses a payment for a moment.

The links are taught in HAS-A vs IS-A (opens in a new tab); here you only spot them.

Follow objects with a trace table

A trace table is a small note of each variable, the object it points to, and that object's field values. Label the objects #1, #2, … in the order new creates them.

Example 3 · Two variables, one object

AliasDemo.javaJava
class Wallet {    String owner;    int balance;
    Wallet(String owner, int balance) {        this.owner = owner;        this.balance = balance;    }
    void add(int amount) {        balance += amount;    }}
public class AliasDemo {    public static void main(String[] args) {        Wallet a = new Wallet("Aarav", 500);        Wallet b = a;        Wallet c = new Wallet("Aarav", 500);        b.add(200);        System.out.println(a.balance);        System.out.println(c.balance);        System.out.println(a == b);        System.out.println(a == c);    }}
Output
700
500
true
false

What this code does

  • Trace table: a → #1, b → #1, c → #2. Only two new, so only two wallets.
  • b.add(200) changes wallet #1, which a also points to. Wallet #2 is a separate object with equal values.

The table catches the most common reading mistake. After Wallet b = a; there is still one wallet, so write a → #1 and b → #1: a change through b shows through a too.

Keep static fields in their own row. There is one copy per class, shared by every object, so every object sees the latest value.

Trace the code

Fill the trace table

class Seat {
static int booked = 0;
String name;
void book(String who) {
name = who;
booked++;
}
}
public class SeatTrace {
public static void main(String[] args) {
Seat s1 = new Seat();
Seat s2 = new Seat();
Seat s3 = s1;
s1.book("Aarav");
s3.book("Diya");
s2.book("Kavya");
System.out.println(s1.name + " " + s2.name + " " + s3.name);
System.out.println("Bookings: " + Seat.booked);
}
}

Variables

booked
0
s1
#1 name=null

Output

(nothing printed yet)

Line 13new Seat() makes object #1; its name starts as null. booked is static: one shared copy, in its own row.

Step 1 of 8
An array like new Item[5] creates one array object with five empty (null) slots. It creates no Item objects.

Follow each call to the method that really runs

For x.method(), first ask which object x points to right now. Java looks for the method in that object's class, then in its parents: dynamic method dispatch (opens in a new tab). While a method runs, its caller waits.

Example 4 · The call stack: callers wait

StackDemo.javaJava
class Engine {    void start() {        System.out.println("Engine starts");    }}
class Cab {    Engine engine = new Engine();
    void ride(String to) {        System.out.println("Ride to " + to + " begins");        engine.start();        System.out.println("Ride to " + to + " ends");    }}
class Rider {    String name;
    Rider(String name) {        this.name = name;    }
    void book(Cab cab) {        System.out.println(name + " books a cab");        cab.ride("Station");        System.out.println(name + " pays");    }}
public class StackDemo {    public static void main(String[] args) {        new Rider("Rohan").book(new Cab());    }}
Output
Rohan books a cab
Ride to Station begins
Engine starts
Ride to Station ends
Rohan pays

What this code does

  • book calls ride, and ride calls start. Each caller waits on the call stack until the call it made finishes.
  • So "Rohan pays" prints last, even though it is written right after cab.ride(...) in book.

Example 5 · Overridden method inside a parent method, plus a static counter

ReadTrapDemo.javaJava
class Account {    static int created = 0;    String id;
    Account(String id) {        this.id = id;        created++;    }
    String type() {        return "Basic";    }
    void show() {        System.out.println(id + " is " + type() + ", accounts: " + created);    }}
class SavingsAccount extends Account {    SavingsAccount(String id) {        super(id);    }
    @Override    String type() {        return "Savings";    }}
public class ReadTrapDemo {    public static void main(String[] args) {        Account a1 = new Account("A1");        a1.show();        Account a2 = new SavingsAccount("S1");        a2.show();        a1.show();    }}
Output
A1 is Basic, accounts: 1
S1 is Savings, accounts: 2
A1 is Basic, accounts: 2

What this code does

  • show lives only in Account, but inside it type() runs the version of the real object: Savings for S1.
  • created is static, so the third line shows 2 even for A1: there is one shared counter.

Java keeps the methods that are still running on the call stack. The newest call is on top and finishes first; then its caller continues from the next line.

Return values come back the same way. In payment.pay(total()), Java runs total() first, then passes its result to pay.

Order of execution

Who prints when?

main runs the three lines at the bottom. Tap the steps in the order they happen.

class Kitchen {
void cook() {
System.out.println("cook");
}
}
class Waiter {
Kitchen kitchen = new Kitchen();
void serve() {
System.out.println("take order");
kitchen.cook();
System.out.println("serve plate");
}
}
// in main:
System.out.println("enter");
new Waiter().serve();
System.out.println("pay bill");

Traps that fool readers

Some programs look simple but hide a surprise. Watch for these four while you trace, and write each one into your trace table the moment you see it.

  • Two variables, one object: changing it through one variable changes what the other sees.
  • A parent method calling an overridden method runs the child version for a child object.
  • A static field is shared; its value is whatever the last change made it.
  • A field of object type starts as null: following it before it is set gives NullPointerException.

Predict the output

Spot the trap

Read the code and pick what it prints.

Round 1 of 3

A parent method, an override and a static counter.

class Member {
static int count;
Member() {
count++;
}
String tag() {
return "member";
}
void show() {
System.out.println(tag() + " " + count);
}
}
class Topper extends Member {
@Override
String tag() {
return "topper";
}
}
public class TrapRound {
public static void main(String[] args) {
Member a = new Topper();
a.show();
new Member();
a.show();
}
}

Next step

Check your understanding

11 quick questions