CSE Roadmap

Core tier · about 2 hours · 7 parts

Part 6 of 7 · 2 min read

Overriding rules in Java

A few mechanics that avoid silent mistakes.

Overriding rules in Java

Mechanics worth knowing (common practice, with EJ's advice where noted):

  • Put @Override on every method meant to override or implement. EJ Item 40 recommends consistent use. If the signature is wrong, the compiler reports it. Without it, a misspelled method silently becomes a new, unused method.
  • Overriding is chosen at run time by the actual object. Overloading (the same name with different parameter types) is chosen at compile time by the declared types. Mixing them up causes surprises.
  • A final method or class cannot be overridden or extended.
  • A private method is not inherited, so it cannot be overridden.
  • Calling an overridable method from a constructor is risky, because the subclass part may not be built yet.

Interview angle

Answer in your head first, then open it.

What is polymorphism?

The same call on a common type runs different code depending on the actual object.

How do you remove a long if-else on type?

Make an interface, one class per branch, and call the method through the interface.

Overloading or overriding?

Overriding is picked at run time by the object. Overloading is picked at compile time by the declared types.

What can go wrong with a subtype?

It may break the parent's promises and surprise callers.

Check yourself: 1. What does @Override protect against? 2. Which of overriding and overloading is decided at compile time? 3. Why avoid calling overridable methods in constructors?

Words you will meet

Word Meaning
Polymorphism Objects of a common type answering the same request in their own ways
Dynamic binding Choosing the operation at run time from the actual object
Override A subclass's own version of an inherited method
Overload Several methods with one name and different parameters
Subtype A type that can stand in for another
Tagged class One class that uses a tag and switch to act as several kinds