Java
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+ supports if (p instanceof UpiPayment u)) to avoid ClassCastException.

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

AspectMethod Overloading (Compile-Time)Method Overriding (Runtime)
WhereSame class (or subclass)Subclass & Superclass
SignatureSame name, different parametersSame name & exact same parameters
Return TypeCan differSame or covariant subtype
BindingStatic binding by compilerDynamic Method Dispatch by JVM

Rules for Method Overriding

  • Visibility cannot be more restrictive (e.g., cannot override public with protected).
  • static, final, and private methods cannot be overridden (static methods are hidden, not dynamically dispatched).
  • Always use @Override so 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+ supports if (p instanceof UpiPayment u)) to avoid ClassCastException.
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)