Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Overriding

    Overriding — a subclass provides its own version of an inherited method, with the same name and parameters.

    Chapter 3 of 126 min read

    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.

    • @Override is 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.

    Java
    // in Question:
    String describe() {
        return "Question: " + text;
    }
    
    // in MultipleChoice:
    @Override
    String describe() {
        return "MCQ -> " + super.describe();
    } // extend the parent's version
    Java
    System.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 it

    Rules for overriding#

    1. Same name and same parameter types.

    2. Return type the same, or a subclass of it (covariant return).

    3. Can't make it less visible (a public method can't be overridden as private).

    4. Can't throw broader checked exceptions (Exceptions and Generics).

    5. static, private and final methods 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
    Wheresame class (or inherited)subclass replaces parent's method
    Parametersdifferentsame
    Decidedat compile time, by argument typesat run time, by the actual object (Ch 4)
    Purposesame operation, different inputs (add(int,int), add(double,double))different behaviour for a subtype
    Also calledcompile-time / static polymorphismruntime / dynamic polymorphism

    Four details interviewers like (run on Java 21.0.8)#

    Java
    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 Student
    Output
    static 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: 1
    1. Static methods are hidden, not overridden: p.who() ran Parent.who because static calls are bound to the reference type at compile time (the compiler warns you to write Parent.who()); p.name() ran Child.name — dynamic dispatch (Ch 4).

    2. Covariant returns use bridge methods: Child.make() returns String, but callers compiled against Parent.make() expect Object, so the compiler adds a hidden bridge method returning Object that calls the String one. Generics use bridges too (Exceptions and Generics Ch 9 on erasure).

    3. Marker interfaces have no methods — Serializable, Cloneable — they only tag a class for some framework to check (instanceof). Annotations are the modern alternative.

    4. Serialisation: Java serialisation writes the fields of Serializable objects; transient fields are skipped (the token came back null); declare a serialVersionUID so compatible class changes don't break old data with InvalidClassException. 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 questions
    1

    What does @Override protect you from?

    Show answer

    Accidentally creating a new method (typo in the name or wrong parameters) when you meant to override one.

    2

    Can you override a static method? A private one?

    Show answer

    No and no (a same-signature static method in a subclass only hides the parent's).

    3

    Overloading vs overriding — which is decided at runtime?

    Show answer

    Overriding.