Read an unfamiliar OOP program
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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); }}Kavya: 91 Kavya: 95
What this code does
Printercomes first in the file, but nothing runs untilmaincreates objects and callsprint.printreceives 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:
- Find
main, the entry point: the method where running starts. - List the classes: for each one, its fields, constructors and methods.
- Mark the links:
extends,implements, fields of another class type. - Walk through
mainline by line. Number each object asnewcreates it:#1,#2. - For each call, jump to the method that really runs, finish it, then come back.
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.
Example 2 · Worked example: a five-class food order
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")); }}Priya ordered 2 items Paid Rs. 130 by UPI (priya@okbank)
What this code does
- Map:
UpiPaymentis-aPayment;Orderhas-aCustomerand hasItems;checkoutuses aPayment. - Trace:
priya → #1,order → #2(customer = #1), two items #3 and #4 go into the array, thencheckoutruns. - In
payment.pay(total()),total()returns 130 first;payruns theUpiPaymentversion because the object is aUpiPayment.
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
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); }}700 500 true false
What this code does
- Trace table:
a → #1,b → #1,c → #2. Only twonew, so only two wallets. b.add(200)changes wallet #1, whichaalso 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
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.
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
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()); }}Rohan books a cab Ride to Station begins Engine starts Ride to Station ends Rohan pays
What this code does
bookcallsride, andridecallsstart. 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(...)inbook.
Example 5 · Overridden method inside a parent method, plus a static counter
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(); }}A1 is Basic, accounts: 1 S1 is Savings, accounts: 2 A1 is Basic, accounts: 2
What this code does
showlives only inAccount, but inside ittype()runs the version of the real object:Savingsfor S1.createdis 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.
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
staticfield 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 givesNullPointerException.
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.
Next step
Check your understanding
11 quick questions