Module 9: PolymorphismBeginner24 min read
Polymorphism: Overloading, Overriding & Dynamic Dispatch
Understand static vs dynamic binding, method overloading vs overriding, upcasting, downcasting, and safe instanceof checks.
Key Takeaways & Core Concepts
- Upcasting:
Payment p = new UpiPayment();(automatic, always safe). - Downcasting: Always guard with
instanceof(Java 16+ supportsif (p instanceof UpiPayment u)) to avoidClassCastException.
Introduction
Polymorphism ("many forms") allows a single interface or base-class reference to behave differently depending on the actual runtime object it points to.
Dynamic Method Dispatch & Safe Pattern Matching
1class Payment {
2 void pay(double amount) { System.out.println("Paying " + amount); }
3}
4class UpiPayment extends Payment {
5 @Override
6 void pay(double amount) { System.out.println("Paid Rs." + amount + " via UPI"); }
7 String provider() { return "BHIM UPI"; }
8}
9
10public class Main {
11 public static void main(String[] args) {
12 Payment p = new UpiPayment(); // Upcasting
13 p.pay(499.0); // Dynamic dispatch
14 if (p instanceof UpiPayment upi) { // Java 16+ pattern matching
15 System.out.println("Provider: " + upi.provider());
16 }
17 }
18}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
18 lines
Note: Even though `p` has compile-time type `Payment`, the JVM invokes `UpiPayment.pay()` based on the runtime object.
Compile-Time vs Runtime Polymorphism
| Aspect | Method Overloading (Compile-Time) | Method Overriding (Runtime) |
|---|---|---|
| Where | Same class (or subclass) | Subclass & Superclass |
| Signature | Same name, different parameters | Same name & exact same parameters |
| Return Type | Can differ | Same or covariant subtype |
| Binding | Static binding by compiler | Dynamic Method Dispatch by JVM |
Rules for Method Overriding
- Visibility cannot be more restrictive (e.g., cannot override
publicwithprotected). static,final, andprivatemethods cannot be overridden (staticmethods are hidden, not dynamically dispatched).- Always use
@Overrideso the compiler catches typos in method signatures.
Upcasting, Downcasting & Pattern Matching instanceof
- Upcasting:
Payment p = new UpiPayment();(automatic, always safe). - Downcasting: Always guard with
instanceof(Java 16+ supportsif (p instanceof UpiPayment u)) to avoidClassCastException.
Practice & AssessmentJava Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)