The Plain Picture#
Your inherited recipe book says "make tea: boil water with milk". Your family makes it differently, so you cross it out and write your own version under the same title. Anyone asking your household to "make tea" gets your version.
The Real Names#
Overriding = a subclass provides its own version of an inherited method, with the same name and parameters.
@Overrideis an annotation (a label for the compiler) saying "I intend to override a parent method". If you misspell the name or get the parameters wrong, the compiler errors instead of silently creating a new method. Always write it.super.method()still lets you call the parent's version from inside yours.
// in Question:
String describe() {
return "Question: " + text;
}
// in MultipleChoice:
@Override
String describe() {
return "MCQ -> " + super.describe();
} // extend the parent's versionSystem.out.println(quiz.get(0).describe()); // MCQ -> Question: Powerhouse of the cell? A) Mitochondria B) Nucleus
System.out.println(quiz.get(1).describe()); // Question: DNA is a protein ← TrueFalse didn't override itRules for overriding#
Same name and same parameter types.
Return type the same, or a subclass of it (covariant return).
Can't make it less visible (a
publicmethod can't be overridden asprivate).Can't throw broader checked exceptions (Exceptions and Generics).
static,privateandfinalmethods can't be overridden. (A static method with the same signature in a subclass hides the parent's one; it doesn't override it — no polymorphism, Ch 4.)
Overloading vs overriding — the classic interview question#
| Overloading (Java Basics Ch 7) | Overriding | |
|---|---|---|
| Where | same class (or inherited) | subclass replaces parent's method |
| Parameters | different | same |
| Decided | at compile time, by argument types | at run time, by the actual object (Ch 4) |
| Purpose | same operation, different inputs (add(int,int), add(double,double)) | different behaviour for a subtype |
| Also called | compile-time / static polymorphism | runtime / dynamic polymorphism |
Four details interviewers like (run on Java 21.0.8)#
static class Parent { static String who() { return "Parent.who"; } String name() { return "Parent.name"; } Object make() { return "an Object"; } }
static class Child extends Parent { static String who() { return "Child.who"; } @Override String name() { return "Child.name"; } @Override String make() { return "a String"; } }
static class Student implements Serializable { private static final long serialVersionUID = 1L; final String name; transient String sessionToken; … }
Parent p = new Child(); p.who(); p.name(); // then reflect on Child.make, and serialise + deserialise a Studentstatic method via a Parent reference to a Child: Parent.who / instance method: Child.name
(static methods are hidden, not overridden: chosen by the reference type at compile time)
Child.make declared as: returns String
Child.make declared as: returns Object <- compiler-generated BRIDGE method
Serializable is a marker interface with 0 methods
after serialise + deserialise: name=asha, sessionToken=null (transient field not saved)
serialVersionUID written in the stream: 1Static methods are hidden, not overridden:
p.who()ranParent.whobecause static calls are bound to the reference type at compile time (the compiler warns you to writeParent.who());p.name()ranChild.name— dynamic dispatch (Ch 4).Covariant returns use bridge methods:
Child.make()returnsString, but callers compiled againstParent.make()expectObject, so the compiler adds a hidden bridge method returningObjectthat calls theStringone. Generics use bridges too (Exceptions and Generics Ch 9 on erasure).Marker interfaces have no methods —
Serializable,Cloneable— they only tag a class for some framework to check (instanceof). Annotations are the modern alternative.Serialisation: Java serialisation writes the fields of
Serializableobjects;transientfields are skipped (the token came backnull); declare aserialVersionUIDso compatible class changes don't break old data withInvalidClassException. Avoid Java serialisation for untrusted input (it has a long history of deserialisation exploits) — prefer JSON/Protobuf (GraphQL, gRPC, WebSockets and SSE (coming soon) Ch 6).
Check yourself
3 questionsWhat does @Override protect you from?
Show answerHide answer
Accidentally creating a new method (typo in the name or wrong parameters) when you meant to override one.
Can you override a static method? A private one?
Show answerHide answer
No and no (a same-signature static method in a subclass only hides the parent's).
Overloading vs overriding — which is decided at runtime?
Show answerHide answer
Overriding.