Trace inheritance and polymorphism
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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).
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
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")); } }}SMS to Arjun Notice to Arjun Email to Arjun
What this code does
- Every element has the declared type
Notification, sosendis allowed on all of them. - At run time each object picks its own version; the plain
Notificationuses the parent's.
Example 2 · super calls back into the child
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()); }}Manager Priya: Rs. 50000
What this code does
e.slip()runsManager.slip, which callssuper.slip(), theEmployeeversion.- Inside
Employee.slip,salary()meansthis.salary().thisis aManager, 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
Variables
- r
- NightRide object
Output
(nothing printed yet)Line 22r is declared Ride, but the object is a NightRide.
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
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); }}bill(Customer) for a premium bill(PremiumCustomer) for a premium bill(PremiumCustomer) for a premium
What this code does
b.bill(c):cis declaredCustomer, so javac picksbill(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.
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
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); }}Basic OS Phone Smart ring Android
What this code does
p.osandp.kind()use the declared typePhone: 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
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(); }}CallDemo.java:22: error: cannot find symbol
a.fetch();
^
symbol: method fetch()
location: variable a of type Animal
1 errorWhat this code does
- javac checks calls against the declared type
Animal, which has nofetch(). The real object does not matter at compile time. - Fix:
if (a instanceof Dog d) { d.fetch(); }gives aDogvariable 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.namereads 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
xalways 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.
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
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(); }}C.run A.run B.show A.show
What this code does
obj.run(): the object is aC, which overridesrun.super.run()goes up toB, which has norun, soA.runruns.- In
A.run,show()isthis.show(). Starting atCand going up, the firstshowis inB; itssuper.show()prints "A.show".
The routine:
- Write the declared type and the real object for every variable.
- For each call, check that the declared type has the method; if not, it is a compile error.
- Pick the overload using the declared types of the arguments.
- Field or static method? Use the declared type. Done.
- Instance method? Start at the real object's class and go up to find that signature.
- 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
Next step
Check your understanding
12 quick questions