ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Method Overriding
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 6.2

Method Overriding

Override rules, covariant return types, access restrictions and @Override

11 min readStage 1 · Foundations14 interview questions
Prerequisites
6.1 Inheritance · 4.4 Methods
Covers
Override rules · Covariant return types · Access restrictions · @Override
Related
6.3 Polymorphism · 6.4 Inheritance Design (LSP) · 7.1 Interfaces (default methods)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

Overriding means a subclass provides its own implementation of an instance method inherited from a superclass or interface, with the same signature. At run time, calls on an object of the subclass execute the subclass version, even through a superclass reference (6.3). Overriding is how subclasses specialise behaviour.

Overriding differs from hiding and overloading in what is chosen and when
Figure 1 — Overriding differs from hiding and overloading in what is chosen and when

2Why It Exists

Inheritance alone gives a subclass its parent's behaviour unchanged; overriding is what lets it specialise that behaviour while still being used through the parent's type. A Manager is paid differently from an Employee, a Circle computes its own area, and a map key decides what equality means for it. Overriding is also how frameworks hand control back to application code: the framework calls a method on its own type, and the application's override runs. Without it, every variation would need a type check in the caller (6.3).

The rules in section 3 exist because that substitution must stay safe: code written against the parent cannot know which override it will meet at run time.

3Core Concepts

Override rules

The compiler enforces a set of rules that together guarantee that the subclass method can be called safely wherever the superclass method could be.

The rules for a valid override
Figure 2 — The rules for a valid override

Static methods are not overridden but hidden: a static method with the same signature in a subclass is selected by the reference's compile-time type, not by the object. Private methods are not inherited, so a same-named method in a subclass is a new, unrelated method. final methods cannot be overridden.

Covariant return types

An overriding method may declare a return type that is a subtype of the overridden method's return type. Invoice.copy() can return Invoice although Document.copy() returns Document, so callers holding an Invoice need no cast. Primitive return types must match exactly.

Invoice.copy() narrows the return type to Invoice
Figure 3 — Invoice.copy() narrows the return type to Invoice

Access restrictions

An override may keep or widen access (protected to public) but never narrow it (public to protected), because code that could call the superclass method through a superclass reference must still be able to call it. Similarly, an override may throw fewer or narrower checked exceptions, never broader or new ones; unchecked exceptions are not restricted by the compiler, but throwing new ones still breaks callers' expectations.

@Override

The @Override annotation asks the compiler to verify that the method really overrides something. Without it, a small mistake — a wrong parameter type, equals(Order o) instead of equals(Object o), a typo in the name — creates a new overload that is silently never called polymorphically. Always use @Override.

4How It Works Internally

An override takes over its parent's entry in the method table, so a virtual call on a subclass object finds the subclass code (6.1). javac checks the rules of section 3 when it compiles the subclass, but the JVM matches methods by name and full descriptor, return type included. At bytecode level a covariant override such as Invoice copy() therefore does not override Document copy(). javac closes the gap with a bridge method: a synthetic Document copy() in Invoice that just calls Invoice copy(), so a call through a Document reference still reaches the override (Figure 4). javap shows both methods:

TERMINAL
$ javap -p -c Invoice
class Invoice extends Document {
  Invoice copy();
    Code:
       0: new           #7  // class Invoice
       3: dup
       4: invokespecial #9  // Method "<init>":()V
       7: areturn
 
  Document copy();
    Code:
       0: aload_0
       1: invokevirtual #10  // Method copy:()LInvoice;
       4: areturn
}
A covariant override and the bridge method javac generates for the old signature
Figure 4 — A covariant override and the bridge method javac generates for the old signature

Generic types are erased to their bounds in the same way, so overriding a method of a generic supertype, such as compareTo(Money) in a class that implements Comparable<Money>, also produces a bridge, compareTo(Object). Bridge methods are flagged as synthetic in the class file; they show up as an extra frame in some stack traces, and reflection-based tools have to skip them when they look for the method a class declares (Example 4).

5APIs / Features / Syntax

The override rules of section 3, side by side:

AspectAllowed in an overrideNot allowed
SignatureSame name and parameter types (after erasure)Other parameter types: that is an overload
Return typeThe same type, or a subtype for references (covariant)A supertype, or a different primitive type
AccessThe same or wider (protected to public)Narrower (public to protected)
Checked exceptionsNone, the same, or narrower onesNew or broader checked exceptions
static methodsHidden by a static method with the same signatureAn instance method with that signature
final methods-Any override
private methods- (not inherited)@Override on a method with the same name
@OverrideOn every override, interface methods included-

Inside an override, super.method() runs the parent's version (6.1). Interfaces follow the same rules for default methods, plus one of their own: a default method may not override equals, hashCode or toString from Object.

6Practical Examples

Example 1 — The classic missing @Override bug

JAVAThe classic missing @Override bug
public class Order {
    // Wrong: overloads equals, does not override it
    public boolean equals(Order other) { return id == other.id; }
}
Set<Order> set = new HashSet<>();
set.add(new Order(1)); set.add(new Order(1));
System.out.println(set.size());      // 2 — uses hashCode() and equals(Object)

public class Order {
    @Override                         // compiler now checks the signature
    public boolean equals(Object o) {
        return o instanceof Order other && id == other.id;
    }
    @Override public int hashCode() { return Long.hashCode(id); }
}

What to notice. The first Order has two problems: equals(Order) is an overload that HashSet never calls, and hashCode() is not overridden at all, so equal orders usually land in different buckets before equals is even consulted. The second version fixes both, and @Override turns any future signature mistake into a compile error. The kit runs both versions: the sets have 2 and 1 elements.

Example 2 — Mini program: overriding equals, hashCode and toString

Problem. The three Object methods that classes override most often are also the easiest to get wrong. This program puts a class that inherits Object's versions next to one that overrides all three, and uses both in a set and a map.

JAVAObjectMethods.java
public class ObjectMethods {
    static class PlainSku {                          // inherits Object's versions
        final String code; final int size;
        PlainSku(String code, int size) { this.code = code; this.size = size; }
    }
 
    static final class Sku {                         // overrides all three
        private final String code; private final int size;
        Sku(String code, int size) { this.code = code; this.size = size; }
 
        @Override public boolean equals(Object o) {
            if (this == o) return true;
            return o instanceof Sku other && size == other.size
                    && code.equals(other.code);
        }
        @Override public int hashCode() { return Objects.hash(code, size); }
        @Override public String toString() { return code + "/" + size; }
    }
 
    public static void main(String[] args) {
        Set<PlainSku> plain = new HashSet<>();
        plain.add(new PlainSku("TEE", 40));
        plain.add(new PlainSku("TEE", 40));
        System.out.println("PlainSku: set size " + plain.size() + ", contains "
                + plain.contains(new PlainSku("TEE", 40)));
 
        Set<Sku> skus = new HashSet<>();
        skus.add(new Sku("TEE", 40));
        skus.add(new Sku("TEE", 40));
        Map<Sku, Integer> stock = new HashMap<>(Map.of(new Sku("TEE", 42), 7));
        System.out.println("Sku:      set size " + skus.size() + ", contains "
                + skus.contains(new Sku("TEE", 40)));
        System.out.println("lookup:   " + stock.get(new Sku("TEE", 42))
                + ", printed as "
                + skus.iterator().next());
    }
}
OUTPUT
PlainSku: set size 2, contains false
Sku:      set size 1, contains true
lookup:   7, printed as TEE/40

Why it behaves this way. Object.equals compares identity and Object.hashCode is derived from identity, so two PlainSku objects with the same data are two different elements and a third one cannot be found. Sku overrides equals to compare the fields, with the parameter type Object that the override needs, and hashCode to combine the same fields, so equal objects have equal hash codes and both the set and the map find them. toString is overridden to print something useful in logs instead of ClassName@hash. A record would generate all three, which is why records are the usual choice for such value classes (4.2).

Example 3 — Hiding versus overriding

JAVAHiding versus overriding
class Parent {
    static String kind() { return "parent"; }
    String name() { return "parent"; }
}
class Child extends Parent {
    static String kind() { return "child"; }       // hides
    @Override String name() { return "child"; }    // overrides
}
Parent p = new Child();
System.out.println(p.kind());   // "parent" — static: chosen by reference type
System.out.println(p.name());   // "child"  — instance: chosen by object

Example 4 — Covariant returns and the bridge method

Problem. Section 4 says that javac adds a bridge method for every covariant override. This program uses the covariant return and then lists the methods Invoice really declares, as reflection sees them.

JAVABridgeDemo.java
public class BridgeDemo {
    static class Document {
        Document copy() { return new Document(); }
    }
    static class Invoice extends Document {
        @Override Invoice copy() { return new Invoice(); }   // covariant return
    }
 
    public static void main(String[] args) {
        Invoice inv = new Invoice().copy();                  // no cast needed
        Document doc = inv;
        System.out.println("class of doc.copy(): "
                + doc.copy().getClass().getSimpleName());
 
        Method[] ms = Invoice.class.getDeclaredMethods();
        Arrays.sort(ms, Comparator.comparing(m -> m.getReturnType().getName()));
        for (Method m : ms)
            System.out.println(m.getName() + "() returns "
                    + m.getReturnType().getSimpleName()
                    + (m.isBridge() ? "  [bridge, synthetic]" : ""));
    }
}
OUTPUT
class of doc.copy(): Invoice
copy() returns Document  [bridge, synthetic]
copy() returns Invoice

Why it behaves this way. new Invoice().copy() needs no cast, because the declared return type is Invoice; through the Document reference the call still runs the override and returns an Invoice. getDeclaredMethods() reports two copy() methods although the source declares one: the second is the bridge, with the return type Document, and isBridge() is true for it. Frameworks that scan methods by reflection, for annotations for example, filter out bridges, or they would see every covariant or generic override twice.

Example 5 — When the parent's behaviour must still run: calling super

Problem. Section 7 lists forgetting super.method() as a common mistake. This program shows why it is easy to miss: both overrides compile and do their own work, and only one of them leaves the object in the state the framework expects.

JAVASuperCall.java
public class SuperCall {
    static final List<String> registry = new ArrayList<>();
 
    static class Component {                        // a framework base class
        protected boolean started;
        /** Subclasses that override must call super.start() first. */
        void start() {
            started = true;
            registry.add(getClass().getSimpleName());   // health checks see it
        }
    }
 
    static class GoodCache extends Component {
        @Override void start() {
            super.start();                          // parent's work first
            System.out.println("GoodCache warmed, started=" + started);
        }
    }
 
    static class BadCache extends Component {
        @Override void start() {                    // forgot super.start()
            System.out.println("BadCache warmed,  started=" + started);
        }
    }
 
    public static void main(String[] args) {
        for (Component c : List.of(new GoodCache(), new BadCache())) c.start();
        System.out.println("registered: " + registry);
    }
}
OUTPUT
GoodCache warmed, started=true
BadCache warmed,  started=false
registered: [GoodCache]
An override replaces the parent's code completely unless it calls super
Figure 5 — An override replaces the parent's code completely unless it calls super

Why it behaves this way. An override replaces the inherited method entirely; nothing of Component.start() runs unless the override calls it. BadCache warms its cache, but it is never marked as started or registered, so health checks and shutdown hooks that rely on the registry ignore it (Figure 5). The Javadoc requirement is the only protection, which is why section 9 recommends a different design for base classes: a final start() that does the framework's work and then calls a protected hook such as onStart(), which subclasses override without being able to skip the rest.

7Common Problems & Mistakes

MistakeWhy it hurtsWhat to do
Missing @OverrideA wrong parameter type creates an overload that is never called polymorphically, such as equals(Order)Annotate every override; enable the compiler or IDE check that requires it
Overriding equals without hashCodeEqual objects get different hash codes, so hash-based collections cannot find themOverride both together, or use a record (Example 2)
An override that changes what the method means, e.g. throws UnsupportedOperationExceptionCode written against the parent fails only when this subclass is passed in, an LSP violation (6.4)Keep the contract, or do not inherit
Calling overridable methods from constructorsThe override runs before the subclass's fields are initialised (4.3)Call only private or final methods from constructors
Forgetting super.method() in a lifecycle callbackThe parent's work silently never happens, e.g. registration or cleanup (Example 5)Call super first, or design the base with a final method and a protected hook
Declaring final a method that a framework proxy must overrideSpring and Hibernate proxies subclass your class at run time; a final method is not intercepted, so @Transactional or lazy loading is silently skippedLeave proxied methods non-final, or depend on an interface (Q12)

8Performance & Production Considerations

  • Overrides cost nothing extra in hot code. The JIT inlines virtual calls when a call site sees one or two classes (6.3); making methods final for speed is unnecessary.
  • Run-time subclasses are everywhere. Spring's class-based proxies, Mockito mocks and Hibernate's lazy proxies work by generating a subclass that overrides your methods. Final classes, final methods and private methods are invisible to them, which shows up as annotations that "do nothing" in production.
  • equals, hashCode and toString run more often than they appear to. Every map lookup, every set insert and every log line calls them. Keep them cheap, never let toString trigger lazy loading or print secrets, and cache the hash code of large immutable objects.

9Architecture & Design Considerations

Every overridable method is an extension point and part of the class's contract. A class designed for inheritance should document, for each overridable method, what overriding it may and may not do, and which other methods call it ("self-use"). Methods that are not intended as extension points should be final, or the class itself should be final.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is method overriding?

A subclass providing its own implementation of an inherited instance method with the same signature, so that calls on subclass objects run the subclass version.

Q2L2 · IntermediateTricky

Can a static method be overridden?

No. A static method with the same signature in a subclass hides the superclass method. Which one runs is decided at compile time by the reference's declared type, not by the object's class.

Q3L2 · IntermediateConcept

What is a covariant return type?

An overriding method returning a subtype of the overridden method's return type, for example Invoice copy() overriding Document copy(). It lets callers avoid casts. javac implements it with a bridge method (Example 4).

Q4L3 · Senior EngineerInternals

Why can an overriding method not reduce visibility or add broader checked exceptions?

Code written against the superclass may call the method through a superclass reference. If the override were less visible or threw new checked exceptions, such calls would become illegal or unhandled, breaking substitutability.

Q5L3 · Senior EngineerTricky

Why should you always use @Override?

It makes the compiler check that the method actually overrides a supertype method. Without it, signature mistakes create silent overloads — equals(Order) instead of equals(Object) is the classic case — that are never called polymorphically.

Q6L3 · Senior EngineerTricky

What makes an override break the superclass contract even though it compiles?

Changing observable behaviour callers rely on: stronger preconditions, weaker guarantees, new exceptions such as UnsupportedOperationException, side effects the contract excludes, or skipping required super calls. The compiler checks signatures only; the contract is a design responsibility (LSP).

Q7L4 · Technical ArchitectDesign

How should a class designed for inheritance document its overridable methods?

State the contract of each overridable method, whether overrides must call super, and which other methods of the class call it internally. Make everything not meant for extension final, and provide protected hooks for the intended variation points only.

Q8L1 · BasicConcept

What is the difference between overriding and overloading?

Overriding replaces an inherited instance method with the same signature in a subclass, and the JVM chooses the version at run time from the object's class. Overloading declares several methods with the same name and different parameter types, and javac chooses one at compile time from the static types of the arguments (4.4). An accidental overload where an override was intended is the classic bug that @Override prevents.

Q9L1 · BasicConcept

Can a constructor be overridden?

No. Constructors are not inherited, so there is nothing to override; each class declares its own and chains to its parent's with super(...) (4.3). A subclass constructor with the same parameter list as a parent constructor is simply that subclass's constructor.

Q10L2 · IntermediateCode

What does this program print?

JAVAOverrideQuiz.java
public class OverrideQuiz {
    static class Parent {
        static String s() { return "Ps"; }
        String i() { return "Pi"; }
        private String p() { return "Pp"; }
        String all() { return s() + " " + i() + " " + p(); }
    }
    static class Child extends Parent {
        static String s() { return "Cs"; }          // hides
        @Override String i() { return "Ci"; }       // overrides
        String p() { return "Cp"; }                 // new: Parent.p is private
    }
 
    public static void main(String[] args) {
        System.out.println(new Child().all());
    }
}

It prints Ps Ci Pp. all() is compiled in Parent. Its call to the static method s() is bound at compile time to Parent.s(), so the hiding method in Child is not used. i() is an instance method that Child overrides, so the call is dispatched on the object and runs Child.i(). p() is private in Parent, so Child.p() is a new, unrelated method and Parent keeps calling its own.

Q11L3 · Senior EngineerInternals

What is a bridge method, and when does javac generate one?

A synthetic method that javac adds to a class so that an override still works at bytecode level, where methods are matched by name and exact descriptor. It is generated for covariant return types, where Invoice copy() needs a Document copy() bridge, and for overrides of generic methods whose erasure differs, such as compareTo(Money) needing compareTo(Object). The bridge just casts if needed and calls the real method. Reflection reports it with isBridge() true (Example 4).

Q12L3 · Senior EngineerScenario

A Spring service method annotated with @Transactional does not roll back when it fails. The method is declared final. Why?

Without an interface, Spring applies @Transactional through a class-based proxy: a generated subclass that overrides the public methods and wraps each call in a transaction. A final method cannot be overridden, so the proxy simply inherits it and calls it without the transactional wrapper; no error is reported. Remove final from the method, and from the class if needed. The same applies to calls from one method of the bean to another through this, which bypass the proxy as well.

Q13L4 · Technical ArchitectTrade-off

Should equals in a non-final class use instanceof or getClass()?

instanceof lets a subclass object be equal to a parent object, which keeps substitutability, but if the subclass adds a field to its own equals, symmetry breaks: the parent says equal, the subclass says not. getClass() keeps equals symmetric by treating different classes as never equal, at the cost of surprising behaviour for harmless subclasses and for framework proxies, whose class differs from the entity's. The cleanest answer is to avoid the question: make value classes final or records, and give entities identity-based equality in one place.

Q14L5 · Solution ArchitectTrade-off

Your team publishes a widely used library class. Do you let users override its methods, or make it final and offer hooks?

Every overridable public method becomes a promise to subclasses you will never see, including how the class's methods call each other, so the library can no longer change its internals freely. Making the class final, with explicit extension points such as strategy interfaces or protected hooks on a small designed base class, keeps those promises few and documented. The cost is less flexibility for unusual use cases, which users can still meet by composition. For a shared library, choose final plus hooks, and open more only when real requests justify it.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Overriding replaces an inherited instance method with the same signature; chosen at run time.
  • Return type may be covariant; access may widen but not narrow; checked exceptions may narrow.
  • Static methods are hidden, not overridden.
  • Always use @Override.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.