Skip to lesson

Practice: OOP Interview Drill

At the end of an OOP round the interviewer mixes everything: explain a concept with an example, trace a puzzle, fix a bug, sketch a small design. The skill being tested is speed with the right rule.

Explain-with-example round: 10 OOP questions

Interviewers love "explain X with an example". Prepare one example per concept from a single domain, so you never search for ideas under pressure. The table uses an online shop.

Example 1 · Ten explain-with-example answers from one domain

Text
Domain: ShopLite, an online shop 1 Encapsulation  Order: private status; cancel() and ship() check the rules. 2 Abstraction    PaymentGateway interface; OrderService calls charge() only. 3 Inheritance    DigitalProduct extends Product, adds downloadLink. 4 Polymorphism   gateways.forEach(g -> g.charge(amount)): UPI or card code. 5 Overloading    price(int qty) and price(int qty, boolean member). 6 Overriding     FestivalOffer overrides discount(int) to give 20% off. 7 Interface vs  PaymentGateway is an interface; BasePayment is abstract with   abstract class validate() and log() shared by all payment types. 8 Composition    OrderService HAS-A Notifier (SMS or email), swappable. 9 equals/hash    Product equal by SKU; hashCode on SKU only.10 Immutability   record Receipt(String id, int amount) for paid orders.
Preparation
One domain, ten ready examples, about 30 seconds each.

What this code does

  • One domain means every example is ready and the interviewer sees a consistent mental model.
  • Replace this domain with your own project's classes if you have one; real code you wrote is the strongest example.

Must know:

  • one domain, one example per concept, real class and method names
  • definition first, example second, benefit third
  • say "for example" early; it signals you understand, not memorised

If you built ShopLite in Stages 4 and 5, use its real classes; code you wrote is the strongest example.

Order of execution

Shape of a 30-second answer

Put the parts of a strong explain-with-example answer in order.

Predict the output: overriding, overloading, polymorphic calls

Dynamic dispatch means the JVM chooses which overridden method runs from the actual object at run time, not from the declared type of the variable.

Mixed puzzles combine every dispatch rule in one program. Work through the five lines before you read the output.

Example 2 · A mixed dispatch puzzle

DispatchPuzzle.javaJava
class Account {    String type = "account";
    Account() {        System.out.println("A: " + describe());        // calls the override    }
    String describe() {        return "basic account";    }
    static String bank() {        return "SBI";    }
    String fee(int amount) {        return "fee(int) " + amount;    }
    String fee(long amount) {        return "fee(long) " + amount;    }}
class StudentAccount extends Account {    String type = "student";    private String college = "IIT";
    @Override    String describe() {        return "student account at " + college;    }
    static String bank() {        return "Canara";    }
    @Override    String fee(int amount) {        return "student fee(int) " + amount / 2;    }}
public class DispatchPuzzle {    public static void main(String[] args) {        Account a = new StudentAccount();        System.out.println("B: " + a.describe());        System.out.println("C: " + a.type + " / " + ((StudentAccount) a).type);        System.out.println("D: " + Account.bank() + " / " + StudentAccount.bank());        System.out.println("E: " + a.fee(100));        System.out.println("F: " + a.fee(100L));    }}
Output
A: student account at null
B: student account at IIT
C: account / student
D: SBI / Canara
E: student fee(int) 50
F: fee(long) 100

What this code does

  • Line A comes from the parent constructor calling an overridden method: the child's describe runs before the child's field college is set, so it prints null. Line B, after construction, shows IIT.
  • B uses the override; C shows fields follow the declared type; D shows static hiding; E picks the int overload, then the override; F picks the long overload, which is not overridden.

Overloads are chosen by the compiler from declared types; overrides are chosen by the JVM from the object. Fields and static methods follow the declared type. A parent method calling an overridable method dispatches to the child.

Must know:

  • step 1: which overload? look at declared argument types
  • step 2: which override? look at the actual object
  • fields and static methods: declared type only
  • constructors calling overridable methods run the child's version before child fields are set

Predict the output

Trace the call

Work through it line by line, then check the reason.

Round 1 of 3

A child calls super.run() while overriding hi().

class A {
String hi() { return "A"; }
String run() { return hi() + "!"; }
}
class B extends A {
@Override
String hi() { return "B"; }
@Override
String run() { return super.run() + "?"; }
}
public class Round1 {
public static void main(String[] args) {
System.out.println(new B().run());
}
}

Fix a broken equals/hashCode and a leaky immutable class

The equality fix is the standard repair for a class that misbehaves in a HashSet: an @Override equals(Object) and a hashCode built from exactly the same fields.

Two fix-it tasks appear again and again: an equals that does not really override, and an "immutable" class that leaks. Say the bug's name aloud before you fix it.

Example 3 · Fixing a broken equals/hashCode

EqualityFix.javaJava
import java.util.HashSet;import java.util.Objects;import java.util.Set;
class BrokenStudent {    final int roll;    BrokenStudent(int roll) { this.roll = roll; }
    public boolean equals(BrokenStudent other) {        // overload, not override; no hashCode        return other != null && roll == other.roll;    }}
class FixedStudent {    final int roll;    FixedStudent(int roll) { this.roll = roll; }
    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        return roll == ((FixedStudent) o).roll;    }
    @Override    public int hashCode() {        return Objects.hash(roll);    }}
public class EqualityFix {    public static void main(String[] args) {        Set<BrokenStudent> broken = new HashSet<>();        broken.add(new BrokenStudent(7));        broken.add(new BrokenStudent(7));
        Set<FixedStudent> fixed = new HashSet<>();        fixed.add(new FixedStudent(7));        fixed.add(new FixedStudent(7));
        System.out.println("broken set size: " + broken.size());        System.out.println("fixed set size:  " + fixed.size());    }}
Output
broken set size: 2
fixed set size:  1

What this code does

  • BrokenStudent has two bugs: equals(BrokenStudent) is an overload that HashSet never calls, and there is no hashCode.
  • FixedStudent overrides equals(Object) with @Override and adds hashCode on the same field, so the duplicate is rejected.

Example 4 · Fixing a leaky immutable class

LeakFix.javaJava
import java.util.ArrayList;import java.util.List;
final class LeakyTimetable {    private final List<String> slots;    LeakyTimetable(List<String> slots) { this.slots = slots; }    List<String> slots() { return slots; }}
final class FixedTimetable {    private final List<String> slots;    FixedTimetable(List<String> slots) { this.slots = List.copyOf(slots); }    List<String> slots() { return slots; }}
public class LeakFix {    public static void main(String[] args) {        List<String> input = new ArrayList<>(List.of("9am Maths", "10am DBMS"));        LeakyTimetable leaky = new LeakyTimetable(input);        FixedTimetable fixed = new FixedTimetable(input);
        input.set(0, "9am Free");        System.out.println("leaky: " + leaky.slots());        System.out.println("fixed: " + fixed.slots());    }}
Output
leaky: [9am Free, 10am DBMS]
fixed: [9am Maths, 10am DBMS]

What this code does

  • The leaky class has final fields and no setters, yet a change to the caller's list shows up inside it: the missing defensive copy.
  • List.copyOf in the constructor gives the fixed class its own unmodifiable list, so later changes outside cannot reach it.

The first: a class with equals(Student) (an overload) or with equals but no hashCode, used in a HashSet. Fix with @Override equals(Object) and a matching hashCode.

The second: a class with final fields and no setters that still changes, because it stores and returns a caller's List. Fix with List.copyOf in the constructor. Name it first: "overload instead of override", "missing defensive copy".

Fix the error

Fix the broken class

Read the real javac error, then pick the line that fixes it.

Round 1 of 2

The Pin class is meant to work in a HashSet, but javac rejects equals.

class Pin {
final int code;
Pin(int code) { this.code = code; }
@Override
public boolean equals(Pin p) { return p != null && code == p.code; }
}

Error

Round1.java:4: error: method does not override or implement a method from a supertype
    @Override
    ^

Design mini-question: shapes with interfaces and composition

Composition means building a class from other objects held in private fields and delegating work to them. A Drawing that holds a list of Shapes is composition.

A common small design question: shapes that compute area and perimeter, and a drawing that totals them. Use an interface for the capability and composition for the drawing.

Example 5 · Shapes with an interface and composition

ShapeDesign.javaJava
import java.util.ArrayList;import java.util.List;
interface Shape {    double area();    double perimeter();}
record Circle(double r) implements Shape {    public double area() { return Math.PI * r * r; }    public double perimeter() { return 2 * Math.PI * r; }}
record Rectangle(double w, double h) implements Shape {    public double area() { return w * h; }    public double perimeter() { return 2 * (w + h); }}
record Square(double side) implements Shape {          // not a Rectangle subclass    public double area() { return side * side; }    public double perimeter() { return 4 * side; }}
class Drawing {    private final List<Shape> shapes = new ArrayList<>();   // HAS-A shapes
    void add(Shape s) {        shapes.add(s);    }
    double totalArea() {        double total = 0;        for (Shape s : shapes) {            total += s.area();        }        return total;    }
    int count() {        return shapes.size();    }}
public class ShapeDesign {    public static void main(String[] args) {        Drawing d = new Drawing();        d.add(new Circle(1));        d.add(new Rectangle(4, 2.5));        d.add(new Square(3));        System.out.printf("%d shapes, total area %.2f%n", d.count(), d.totalArea());        System.out.printf("Square perimeter %.1f%n", new Square(3).perimeter());    }}
Output
3 shapes, total area 22.14
Square perimeter 12.0

What this code does

  • Shape is the abstraction; each record is immutable and implements it; Drawing composes shapes in a private list and exposes only add, totalArea and count.
  • Square is its own record, so there is no Liskov problem, and adding a Triangle later is one new record: open/closed.

A strong answer: interface Shape { double area(); double perimeter(); }, immutable records Circle, Rectangle and Square implementing it (no Square extends Rectangle, to avoid the Liskov trap), and a Drawing that HAS-A List<Shape>, with add and totalArea. Mention open/closed: a new shape is one new record.

Find the bug

Weak line in the design

Tap the line a reviewer would flag.

Drawing holds shapes. Which line breaks encapsulation?

Round 1 of 2

Next step

Check your understanding

12 quick questions