Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 201 ยท Object-Oriented Programming

Polymorphism and Method Overriding

Learn Java polymorphism - method overriding with @Override, dynamic dispatch, overriding rules, overloading vs overriding, upcasting, downcasting and instanceof.

Polymorphism ("many forms") means one piece of code can work with objects of many different classes, and each object responds in its own way. A loop over a List<PaymentMethod> calls fee(amount) on every element; a card computes a card fee, a wallet a wallet fee, a bank transfer a flat charge. The loop doesn't know or care which kind it has. Add a new payment method next year, and the loop works with it unchanged.

The machinery behind this is method overriding plus dynamic dispatch: a subclass replaces an inherited method with its own version, and at run time Java calls the version that belongs to the object's actual class, not to the type of the variable. This lesson covers both, the precise rules for a valid override, the difference between overriding and overloading (a favorite source of puzzles), and how to move between types safely with upcasting, downcasting and instanceof.

Overriding and dynamic dispatch

A subclass overrides a method by declaring one with the same name and parameter types as an inherited method. Mark it with @Override:

Java One loop, three behaviors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The variable method has the declared type (also static type) PaymentMethod. The objects it refers to have the runtime types Card, Wallet and BankTransfer. Two separate questions are answered by two different types:

  • Which methods can I call? Decided by the compiler, from the declared type. method.fee(...) compiles because PaymentMethod has fee.
  • Which version runs? Decided at run time, from the actual object. That's dynamic dispatch (also late binding). BankTransfer doesn't override fee, so it gets the inherited version.

Dynamic dispatch applies to every instance method call in Java that isn't private, static or final, and you don't need any special keyword to enable it. (C++ programmers: every such method is effectively virtual.)

Why this matters

Without polymorphism, the loop would need an if/else chain or a switch on the type, and every such chain in the program would need editing whenever a new payment method appears. With polymorphism, the knowledge of "how a wallet computes its fee" lives in one place, the Wallet class, and new types plug in without touching existing code. That's the open/closed principle (SOLID) in action.

@Override: let the compiler check you

@Override is optional, but always write it. It tells the compiler "this method must override something", and the compiler refuses if it doesn't. Without it, a typo or a wrong parameter type silently creates a new method instead of overriding the old one. The classic victim is equals:

Java An equals that doesn't override equals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line prints true, the next two print false. List.contains calls equals(Object), which Seat never overrode, so it falls back to Object.equals, which only compares references. Put @Override on the method and the compiler reports method does not override or implement a method from a supertype, pointing straight at the bug. The correct signature is public boolean equals(Object o) (The Object Class).

The rules for overriding

For a method in a subclass to override one in a superclass:

Rule Detail
Same name and parameter types Parameter names don't matter; types and order do. Different parameters make it an overload.
Return type: same or a subtype Covariant return types: an override may return a more specific type. Primitive return types must match exactly.
Access: same or wider protected can become public; public can't become protected (Access Modifiers).
Checked exceptions: same, fewer or narrower An override can't declare new or broader checked exceptions. Unchecked exceptions are unrestricted.
Not final, private or static final methods can't be overridden; private ones aren't inherited, so a same-named method is unrelated; static ones are hidden, not overridden.

The logic behind all of them: code written against the parent type must keep working when handed a subclass object. A caller who expects a public method returning an Animal and throwing at most IOException must never be surprised.

Java Covariant return types and widened access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Invoice.copy() returns Invoice instead of Document, and that's a valid override because every Invoice is a Document. Callers who know they have an Invoice get an Invoice back without casting. The JDK does the same in many places. For example, the Appendable interface declares append returning Appendable, and StringBuilder overrides it to return StringBuilder, which is what makes its chained calls possible.

Overloading vs overriding

The two words sound alike but work at different times:

Overloading Overriding
What Same name, different parameters, usually in one class Same name and parameters, in a subclass
Chosen At compile time, from the declared types of the arguments At run time, from the actual type of the object
Purpose Convenience: one name for related operations Specialization: each type behaves its own way

The combination produces a well-known puzzle. Can you predict the four lines before running it?

Java Overloads are picked at compile time, overrides at run time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

vet.treat(pet) picks treat(Animal), because the compiler only knows pet is an Animal, even though the object is a Dog. Inside, a.sound() still prints Woof: the overload was fixed at compile time, but the override is chosen at run time. Overload resolution has more rules, such as widening, boxing and varargs, covered in Method Overloading.

Fields and static methods aren't polymorphic

Only instance methods are dispatched dynamically. A field with the same name in a subclass hides the parent's field, and which one you read depends on the declared type (The super Keyword has a demo). A static method with the same signature in a subclass also hides the parent's one:

Java
class Parent { static String id() { return "Parent"; } }
class Child extends Parent { static String id() { return "Child"; } }

Parent p = new Child();
p.id();          // "Parent": static calls use the declared type (and should be written Parent.id())

Adding @Override to Child.id() is a compile error, which is one more way the annotation keeps you honest.

Upcasting and downcasting

Upcasting converts a reference to a supertype: Animal a = new Dog();. It's always safe, so it happens automatically. You lose access to subclass-only methods through that variable, but not the subclass behavior: overrides still run.

Downcasting goes the other way: Dog d = (Dog) a;. It needs an explicit cast, and the JVM checks it at run time. If the object isn't actually a Dog (or a subclass of Dog), the cast throws ClassCastException. Casting never changes the object; it only changes how the compiler lets you treat the reference.

Check first with instanceof. Since Java 16, a type pattern checks and casts in one step and gives you a variable of the right type:

Java Downcasting safely with instanceof patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The pattern variable dog exists only where the test is known to be true, so you can't accidentally use it in the else branch. It also works after &&, as in the Cat line. The compiler rejects casts that can never succeed, such as casting a String to an Integer, but between related classes it has to trust you until run time.

Frequent downcasting is a design smell. If you keep asking "is it a Dog? is it a Cat?", the behavior probably belongs in an overridden method instead: give Animal a method and let each subclass implement it. The exception is closed hierarchies where you want to handle each case in one place; that's what sealed classes and pattern matching with switch are designed for.

Polymorphism beyond classes

Everything here works the same with interfaces, and in modern Java that's where you'll use polymorphism most: List<String> names = new ArrayList<>(); declares the interface type and picks the implementation once. Any code that accepts a List works with ArrayList, LinkedList or an immutable List.of(...). Abstract classes let a superclass declare a method without implementing it, forcing every subclass to override it. Both are coming up next: Abstraction and Abstract Classes and Interfaces.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. class A { String hi() { return "A"; } }, class B extends A { @Override String hi() { return "B"; } }. What does A x = new B(); IO.println(x.hi()); print?

    Instance methods are dispatched on the actual object. x is declared as A, but the object is a B, so B's override runs.
  2. 2. What does @Override do?

    The annotation is a check. If the signature doesn't match a supertype method, compilation fails instead of silently creating a new overload.
  3. 3. A parent method is protected Number value(). Which override is valid?

    An override may widen access (protected to public) and narrow the return type to a subtype (Integer is a Number). It can't reduce access, widen the return type, or switch to a primitive.
  4. 4. Overloads void print(Object o) and void print(String s) exist. What runs for Object o = "hi"; print(o);?

    Overload resolution happens at compile time using the declared types of the arguments. o is declared as Object, so print(Object) is chosen.
  5. 5. Animal a = new Cat(); Dog d = (Dog) a; where Cat and Dog both extend Animal. What happens?

    The compiler allows the cast because an Animal might be a Dog. At run time the JVM sees the object is a Cat and throws ClassCastException. Test with instanceof first.

Summary

  • Polymorphism lets one piece of code work with many types; each object responds with its own overridden methods.
  • The declared type decides which methods you may call; the object's runtime type decides which version runs (dynamic dispatch).
  • Always write @Override; it turns signature mistakes, like equals(Seat), into compile errors.
  • An override keeps the name and parameter types, may return a subtype (covariant return), may widen but not narrow access, and may not add broader checked exceptions.
  • Overloads are chosen at compile time from declared argument types; overrides at run time from the object. Fields and static methods are hidden, not overridden.
  • Upcasting is automatic and safe; downcasting needs a cast and can throw ClassCastException. Use instanceof patterns (if (a instanceof Dog d)), and prefer overridden methods to type checks.

Next: Abstraction and Abstract Classes, where a superclass declares what every subclass must do without saying how.