Intermediate · Inheritance, polymorphism and interfaces · topic 22 of 60 · 30 min
Overriding and polymorphism
Explanation
Overriding
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.
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.
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!Overloading versus overriding
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or inherited) | Subclass replaces parent method |
| Parameters | Must differ | Must be the same |
| Chosen | At compile time, by argument types | At run time, by the object's class |
| Annotation | None | @Override |
| Example | add(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.
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
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.
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 automaticallyPractice (0/3 done)
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());
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;
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Abstract classesInheritance, polymorphism and interfaces · same module
- InterfacesInheritance, polymorphism and interfaces · same module
- Virtual functions and polymorphismC++ Programming (modern C++ and DSA) · Operator overloading, inheritance and polymorphism
- Abstract classes and polymorphismC# and .NET · Inheritance, interfaces and records
- Inheritance and interfacesKotlin and Android App Development · Classes, objects and collections
- Inheritance and compositionPython Programming · Object-oriented programming
Questions people ask about this
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.
When is the overridden method chosen?Related
Answer: At run time by the object's actual type
Virtual dispatch happens at run time.
What is polymorphism?Related
Answer: One call behaving differently depending on the actual object
The overridden function of the real object runs.
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.
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
- 3 more topics in “Inheritance, polymorphism and interfaces” before its exam: Abstract classes, Interfaces, Packages and access modifiers.
- Module 5 exam: Inheritance, polymorphism and interfaces · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Exceptions and generics. 60 topics left in the course before the final exam.