Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most polymorphism bugs are not compile errors: the program runs, but the wrong version runs. Knowing the few patterns behind them makes every override and every trace quicker.
Mistakes and fixes at a glance
The most common slip: a child method that was meant to override, but its parameters differ. It quietly becomes an overload, and the parent version keeps running.
Example 1 · Bug: an overload instead of an override
class Alert { void send(String msg) { System.out.println("Notice board: " + msg); }}
class SmsAlert extends Alert { void send(String msg, boolean urgent) { System.out.println("SMS: " + msg); }}
public class OverloadBugDemo { public static void main(String[] args) { Alert a = new SmsAlert(); a.send("Exam postponed"); }}Notice board: Exam postponed
What this code does
send(String, boolean)has an extra parameter, so it overloads instead of replacingsend(String).- The call matches
send(String), whichSmsAlertnever overrode. Write@Override void send(String msg)in the child and the SMS line prints.
Review: The @Override annotation (opens in a new tab). The other common mistakes, each with what goes wrong and the fix:
method does not override or implement a method from a supertype→ the name, capital letters or parameter types differ, or the parent method is private → match the parent exactly. Review: @Override (opens in a new tab)attempting to assign weaker access privileges,return type ... is not compatible→ keep the access at least as open and the primitive return type the same. Review: Method overriding (opens in a new tab)overridden method is finaloroverridden method is static→ these cannot be overridden; add a new method. Review: Method overriding (opens in a new tab)StackOverflowErrorfrom an override → the override calls itself; writesuper.method(...). Review: super.method() (opens in a new tab)method total(int) is already defined→ only the return type or parameter names differ. Review: Overloading vs overriding (opens in a new tab)cannot find symbol ... variable p of type Paymentorincompatible types→ the reference type decides what you may call; a parent object never fits a child variable. Review: Upcasting (opens in a new tab)- A field or
staticmethod read through a parent reference gives the parent's value → use an overridden instance method. Review: Dynamic method dispatch (opens in a new tab)
Mistakes that compile
Two more bugs give no error at all. A child "overrides" a private parent method, so the parent's code still calls its own copy; and a child repeats a field, which parent code never sees.
Example 2 · Two silent bugs
class Account { int rate = 4;
private String type() { return "Account"; }
void show() { System.out.println(type() + " at " + rate + "%"); }}
class FixedDeposit extends Account { int rate = 7;
String type() { return "Fixed deposit"; }}
public class SilentBugsDemo { public static void main(String[] args) { Account a = new FixedDeposit(); a.show(); }}Account at 4%
What this code does
type()inAccountis private, so the child'stype()is a separate method andshow()calls the parent's own copy.- The child's
rateis a second field.show()lives inAccount, so it readsAccount'srate.
Example 3 · The fixed version
class Account { String type() { return "Account"; }
int rate() { return 4; }
void show() { System.out.println(type() + " at " + rate() + "%"); }}
class FixedDeposit extends Account { @Override String type() { return "Fixed deposit"; }
@Override int rate() { return 7; }}
public class FixedBugsDemo { public static void main(String[] args) { Account a = new FixedDeposit(); a.show(); }}Fixed deposit at 7%
What this code does
- Both values now come from overridable instance methods, so
show()gets the object's versions. @Overrideon both child methods proves to javac that they really override.
Both look like overriding but are not: private methods are not inherited and fields are not dispatched. The fix is the same each time: one overridable instance method in the parent, with @Override on the child's version so javac confirms it.
Spot the bug
Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: does the signature match exactly, is it an instance method, and which type does the compiler see?
Find the bug
Find the polymorphism bug
Select the line that is wrong.
SmsAlert should replace Alert's void send(String msg).
Round 1 of 5Trace before you guess
When the output surprises you, trace it. Check the reference type first, then start at the object's class and walk up. A super. call always starts one level above the current class.
Trace the code
Trace dispatch and super
Variables
- t
- Ticket object
Output
(nothing printed yet)Line 17t points to a plain Ticket.
Finish up
Mark complete & continue
Next: Must-do problems: Polymorphism