Skip to lesson

Trace inheritance and polymorphism

Every polymorphism puzzle comes down to two questions asked at two moments. At compile time, the variable type decides which method you may call and which overload is picked. At run time, the real object decides which overridden version runs.

Two moments, two deciders

When javac reads p.pay(amount), it knows only the declared types: the type of the variable p and of the argument. It checks that such a method exists and picks the exact signature (name plus parameter types).

Java
Notification n = new Sms();System.out.println(n.send("Kavya"));// compile time: n is a Notification, so javac checks that Notification has send(String)// run time: the object is an Sms, so Sms's send(String) runs and prints "SMS to Kavya"

When the program runs, Java knows the real object. For an instance method, it takes the signature javac picked and finds the version of it in the object's class, or the nearest parent that has it. Both moments were taught in Overloading vs overriding (opens in a new tab); this lesson applies them to puzzles.

  • Is the call allowed? → the variable type (compile time).
  • Which overload? → the declared argument types (compile time).
  • Which overriding version? → the real object's class (run time).

Overriding: the object decides, even inside super calls

To find the method that runs, start at the object's class and move up until you find it, whether the call is in main or inside a parent method. super.method() is the one exception: it starts the search one class higher.

Example 1 · Dynamic dispatch in a loop

DispatchDemo.javaJava
class Notification {    String send(String to) {        return "Notice to " + to;    }}
class Sms extends Notification {    @Override    String send(String to) {        return "SMS to " + to;    }}
class Email extends Notification {    @Override    String send(String to) {        return "Email to " + to;    }}
public class DispatchDemo {    public static void main(String[] args) {        Notification[] list = { new Sms(), new Notification(), new Email() };        for (Notification n : list) {            System.out.println(n.send("Arjun"));        }    }}
Output
SMS to Arjun
Notice to Arjun
Email to Arjun

What this code does

  • Every element has the declared type Notification, so send is allowed on all of them.
  • At run time each object picks its own version; the plain Notification uses the parent's.

Example 2 · super calls back into the child

SuperDemo.javaJava
class Employee {    String name;
    Employee(String name) {        this.name = name;    }
    int salary() {        return 30000;    }
    String slip() {        return name + ": Rs. " + salary();    }}
class Manager extends Employee {    Manager(String name) {        super(name);    }
    @Override    int salary() {        return super.salary() + 20000;    }
    @Override    String slip() {        return "Manager " + super.slip();    }}
public class SuperDemo {    public static void main(String[] args) {        Employee e = new Manager("Priya");        System.out.println(e.slip());    }}
Output
Manager Priya: Rs. 50000

What this code does

  • e.slip() runs Manager.slip, which calls super.slip(), the Employee version.
  • Inside Employee.slip, salary() means this.salary(). this is a Manager, so it returns 30000 + 20000.

But inside that parent method, a call like salary() is really this.salary(), and this is still the child object, so the child's version runs. Many puzzles test exactly this callback.

Trace the code

Follow the callback

class Ride {
int perKm() {
return 12;
}
int fare(int km) {
return 50 + km * perKm();
}
}
class NightRide extends Ride {
@Override
int perKm() {
return 18;
}
@Override
int fare(int km) {
System.out.println("Night charges apply");
return super.fare(km) + 30;
}
}
public class RideTrace {
public static void main(String[] args) {
Ride r = new NightRide();
System.out.println("Fare: Rs. " + r.fare(10));
}
}

Variables

r
NightRide object

Output

(nothing printed yet)

Line 22r is declared Ride, but the object is a NightRide.

Step 1 of 8

Overloading: the declared types decide

Overloads share a name but differ in parameter types. javac picks one from the declared types of the arguments, before the program runs: with Customer c = new PremiumCustomer();, the call bill(c) picks bill(Customer).

Example 3 · Overload by declared type, override by object

OverloadDemo.javaJava
class Customer {    String level() {        return "regular";    }}
class PremiumCustomer extends Customer {    @Override    String level() {        return "premium";    }}
class Billing {    void bill(Customer c) {        System.out.println("bill(Customer) for a " + c.level());    }
    void bill(PremiumCustomer p) {        System.out.println("bill(PremiumCustomer) for a " + p.level());    }}
public class OverloadDemo {    public static void main(String[] args) {        Billing b = new Billing();        Customer c = new PremiumCustomer();        PremiumCustomer p = new PremiumCustomer();        b.bill(c);        b.bill(p);        b.bill((PremiumCustomer) c);    }}
Output
bill(Customer) for a premium
bill(PremiumCustomer) for a premium
bill(PremiumCustomer) for a premium

What this code does

  • b.bill(c): c is declared Customer, so javac picks bill(Customer), although the object is premium.
  • Inside it, c.level() is an overridden method, so the object decides: "premium".
  • A cast changes the declared type of the expression, so bill((PremiumCustomer) c) picks the other overload.

After javac picks a signature, overriding can still change which body of that signature runs. In puzzles, work in this order: first choose the signature from the declared types, then find its version in the real object's class.

Predict the output

Which overload?

Read the code and pick what it prints.

Round 1 of 2

One overload takes Object, one takes String.

class Printer {
void print(Object o) {
System.out.println("Object");
}
void print(String s) {
System.out.println("String");
}
}
public class NullRound {
public static void main(String[] args) {
Printer p = new Printer();
Object doc = "Resume";
p.print(doc);
p.print(null);
}
}

What is not polymorphic

Only overridden instance methods are chosen by the object. Fields, static methods and private methods are fixed at compile time, by the declared type or by the class the call is written in.

Example 4 · Fields and static methods follow the variable type

HidingDemo.javaJava
class Phone {    String os = "Basic OS";
    static String kind() {        return "Phone";    }
    String ring() {        return "Phone ring";    }}
class SmartPhone extends Phone {    String os = "Android";
    static String kind() {        return "SmartPhone";    }
    @Override    String ring() {        return "Smart ring";    }}
public class HidingDemo {    public static void main(String[] args) {        Phone p = new SmartPhone();        System.out.println(p.os);        System.out.println(p.kind());        System.out.println(p.ring());        System.out.println(((SmartPhone) p).os);    }}
Output
Basic OS
Phone
Smart ring
Android

What this code does

  • p.os and p.kind() use the declared type Phone: fields are hidden and static methods are hidden, never overridden.
  • Only ring(), an overridden instance method, follows the real object. The cast reaches the child's own field.

Example 5 · Mistake: calling a child-only method through a parent variable

CallDemo.javaJava
class Animal {    String sound() {        return "...";    }}
class Dog extends Animal {    @Override    String sound() {        return "Woof";    }
    void fetch() {        System.out.println("Fetching the ball");    }}
public class CallDemo {    public static void main(String[] args) {        Animal a = new Dog();        System.out.println(a.sound());        a.fetch();    }}
Sample compiler output
CallDemo.java:22: error: cannot find symbol
        a.fetch();
         ^
  symbol:   method fetch()
  location: variable a of type Animal
1 error

What this code does

  • javac checks calls against the declared type Animal, which has no fetch(). The real object does not matter at compile time.
  • Fix: if (a instanceof Dog d) { d.fetch(); } gives a Dog variable for the call.

The four cases, as Field hiding vs method overriding (opens in a new tab) showed:

  • Fields: a child field with the same name hides the parent's; p.name reads the field of the variable's type.
  • Static methods: a child static method with the same signature hides, not overrides; p.kind() uses the variable's type.
  • Private methods: a child cannot see them, so a same-named child method is a new method, not an override.
  • Inside a parent method, a plain field name like x always means the parent's own field.

Fix the error

Overrides that cannot happen

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

Round 1 of 3

The viva should have its own maximum marks.

class Exam {
private int maxMarks() {
return 100;
}
}
class Viva extends Exam {
@Override
int maxMarks() {
return 50;
}
}

Error

Viva.java:7: error: method does not override or implement a method from a supertype
    @Override
    ^
@Override on a method that does not really override (for example a static or private one) is a compile error. It is a cheap safety check.

A routine for any puzzle

Use the same six steps for every polymorphism question, and write each answer down instead of keeping it in your head. Here they are on a classic three-level puzzle.

Example 6 · Interview puzzle: three levels and super

LevelsDemo.javaJava
class A {    void show() {        System.out.println("A.show");    }
    void run() {        System.out.println("A.run");        show();    }}
class B extends A {    @Override    void show() {        System.out.println("B.show");        super.show();    }}
class C extends B {    @Override    void run() {        System.out.println("C.run");        super.run();    }}
public class LevelsDemo {    public static void main(String[] args) {        A obj = new C();        obj.run();    }}
Output
C.run
A.run
B.show
A.show

What this code does

  • obj.run(): the object is a C, which overrides run. super.run() goes up to B, which has no run, so A.run runs.
  • In A.run, show() is this.show(). Starting at C and going up, the first show is in B; its super.show() prints "A.show".

The routine:

  1. Write the declared type and the real object for every variable.
  2. For each call, check that the declared type has the method; if not, it is a compile error.
  3. Pick the overload using the declared types of the arguments.
  4. Field or static method? Use the declared type. Done.
  5. Instance method? Start at the real object's class and go up to find that signature.
  6. Inside the method, repeat for every call; super. starts one class higher.

Predict the output

Interview puzzles

Read the code and pick what it prints.

Round 1 of 2

class A {
String who() {
return "A";
}
void hello() {
System.out.print(who() + " ");
}
}
class B extends A {
@Override
String who() {
return "B";
}
}
class C extends B {
@Override
void hello() {
System.out.print("C ");
super.hello();
}
}
public class Puzzle1 {
public static void main(String[] args) {
A[] list = { new C(), new B(), new A() };
for (A x : list) {
x.hello();
}
}
}

Next step

Check your understanding

12 quick questions