Skip to content

Intermediate · Inheritance, polymorphism and interfaces · topic 22 of 60 · 30 min

Overriding and polymorphism

Explanation

A subclass can override an inherited method with its own version, marked @Override. Polymorphism means a parent-type variable can hold any subclass object, and calling a method runs the subclass's version chosen at run time (dynamic dispatch). instanceof with pattern matching safely checks and casts to a subclass when needed.

Overriding

java
class Notification {
    String send(String to, String text) { return "Sending to " + to; }
}
class Sms extends Notification {
    @Override
    String send(String to, String text) {
        return "SMS to " + to + ": " + text.substring(0, Math.min(160, text.length()));
    }
}
class Email extends Notification {
    @Override
    String send(String to, String text) { return "Email to " + to + " with subject"; }
}

Rules for overriding: the same name and parameter types; the return type must be the same or a subtype (a covariant return); the access cannot be more restrictive (a public method cannot become private); and it cannot throw broader checked exceptions. @Override makes the compiler verify all this.

Polymorphism and dynamic dispatch

Polymorphism ("many forms") lets one variable of a parent type refer to objects of different subclasses. When you call an overridden method, the JVM looks at the ACTUAL object at run time and runs that class's version. This is dynamic dispatch. The calling code does not need to know which subclass it has.

java
Notification[] channels = { new Sms(), new Email(), new Sms() };
for (Notification n : channels) {
    System.out.println(n.send("Asha", "Your order has shipped"));   // each runs ITS OWN send
}

Static type and dynamic type

In Notification n = new Sms(); the static type (the variable's declared type) is Notification; the dynamic type (the object's real class) is Sms. The compiler uses the static type to decide which methods you are ALLOWED to call; the JVM uses the dynamic type to decide which overridden version RUNS.

java
Notification n = new Sms();     // upcasting: automatic and always safe
n.send("Ravi", "Hi");           // runs Sms.send
// n.smsOnlyMethod();           // compile error: Notification has no such method

if (n instanceof Sms s) {       // pattern matching for instanceof (Java 16+)
    s.smsOnlyMethod();          // s is already cast to Sms
}
Email e = (Email) n;            // compiles, but throws ClassCastException at run time!
Careful: Downcasting without checking (Email e = (Email) n;) throws ClassCastException when the object is not really an Email. Check with instanceof first, or better, redesign so you call an overridden method instead of checking types.

Overloading versus overriding

OverloadingOverriding
WhereSame class (or inherited)Subclass replaces parent method
ParametersMust differMust be the same
ChosenAt compile time, by argument typesAt run time, by the object's class
AnnotationNone@Override
Exampleadd(int, int) / add(double, double)Sms.send overrides Notification.send

Static methods and fields are NOT polymorphic: a static method with the same signature in a subclass hides the parent's, and which one runs depends on the static type. Fields are also chosen by the static type. Only instance methods are dispatched dynamically.

Think of it like this: Polymorphism is like a TV remote's power button. You press the same button (call send), but a Samsung TV and an LG TV each switch on in their own way (each class's override). You do not need a different remote for each brand.
Tip: If you find yourself writing if (x instanceof A) … else if (x instanceof B) … everywhere, move that behaviour into an overridden method of A and B. That is the main point of polymorphism.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Overriding and polymorphism · 1/6

Overriding and polymorphism

In this lesson you will override methods and use polymorphism.

Prefer a video by a teacher? Find free videos on “java method overriding polymorphism dynamic dispatch instanceof pattern” on YouTube ↗

In real life: Payment methods at checkout

An e-commerce checkout supports UPI, card and net banking. The checkout code holds a Payment reference and calls pay(amount). Adding a new method, such as BNPL ("buy now pay later"), means writing one new subclass; the checkout code does not change.

java
abstract class Payment { abstract String pay(double amount); }
class Upi extends Payment { String pay(double a) { return "Collect request for Rs " + a + " sent to UPI app"; } }
class Card extends Payment { String pay(double a) { return "Redirecting to 3-D Secure for Rs " + a; } }

Payment p = userChoseUpi ? new Upi() : new Card();
System.out.println(p.pay(1499));   // the right version runs automatically

Practice (0/3 done)

Task 1 · Question

What does this print? class A { String who() { return "A"; } } class B extends A { String who() { return "B"; } } … A x = new B(); System.out.println(x.who());

Task 2 · Question

Which line throws ClassCastException? class Animal {} class Dog extends Animal {} class Cat extends Animal {} 1: Animal a = new Dog(); 2: Dog d = (Dog) a; 3: Animal b = new Cat(); 4: Dog e = (Dog) b;

Task 3 · Code · Javascript

The same polymorphism idea in JavaScript, which runs here: write classes Notification (send(to) returns "Sending to <to>"), Sms and Email that extend it and override send to return "SMS to <to>" and "Email to <to>". Then write sendAll(channels, to) that returns an array of each channel's send result, without checking types.

Quick quiz

Question 1

1.When is the overridden method to run chosen?

Question 2

2.A public method in the parent is overridden as private in the child. What happens?

Question 3

3.Are static methods polymorphic?

Question 4

4.Object o = "hi"; if (o instanceof String s) … What is s?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

When is the overridden method to run chosen?

Answer: At run time, based on the actual object

That is dynamic dispatch.

A public method in the parent is overridden as private in the child. What happens?

Answer: Compile error: weaker access

An override cannot reduce visibility.

Are static methods polymorphic?

Answer: No, they are hidden, not overridden

Static methods are chosen by the static type.

Object o = "hi"; if (o instanceof String s) … What is s?

Answer: o cast to String

Pattern matching binds s as the String when the test passes.

Which call is polymorphic?Related

Answer: void f(const Shape& s) { s.area(); }

Calls through references (or pointers) use dynamic dispatch.

From Virtual functions and polymorphism

When is the overridden method chosen?Related

Answer: At run time by the object's actual type

Virtual dispatch happens at run time.

From Abstract classes and polymorphism

What is polymorphism?Related

Answer: One call behaving differently depending on the actual object

The overridden function of the real object runs.

From Inheritance and interfaces

A child class defines speak() and so does its parent. Which runs for child.speak()?Related

Answer: The child's version

Python looks for the method on the child first. This is overriding.

From Inheritance and composition

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 3 more topics in “Inheritance, polymorphism and interfaces” before its exam: Abstract classes, Interfaces, Packages and access modifiers.
  2. Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.

← Previous: Inheritance with extends