๐ŸŽฏ What you will learn

Inheritance gives you reuse. Polymorphism gives you flexibility. Together they let you write code that operates on a parent type and automatically does the right thing for every subtype โ€” without if/else chains. By the end of this lesson you will understand:

  • Polymorphism โ€” one variable, many object types; one call, many behaviours
  • Dynamic dispatch โ€” how the JVM picks the correct override at runtime
  • abstract methods and abstract classes
  • Overriding toString() for clean object printing
  • Java 21 pattern-matching instanceof โ€” typed local variables without casting
๐Ÿ’ผ Interview reality: "What is the difference between compile-time and runtime polymorphism?" appears in every intermediate Java interview. Overloading = compile-time. Overriding = runtime. This lesson covers runtime polymorphism end-to-end.

๐ŸŽญ What is polymorphism?

Polymorphism means "many forms." In Java: one variable of a parent type (Payment p) can hold any subclass instance (UpiPayment, CardPayment). When you call p.process(), Java looks up the actual runtime type and calls the right override โ€” not the parent version. This is called dynamic dispatch and happens automatically.

Key idea: You write code against the parent type. Java ensures the correct subclass implementation runs at runtime. No if/else, no manual type checks โ€” just call the method and the object handles it.

๐Ÿ’ณ Real-world scenario

๐Ÿ’ณ
Real-world scenario ยท BoraPay
BoraPay โ€” Wanjiku's payment dispatcher (Nairobi)

BoraPay handles UPI, card, and net banking payments across East Africa. Wanjiku, a backend engineer in Nairobi, stores all pending transactions in a single queue regardless of their payment method, then calls process() on each โ€” the right implementation runs automatically based on the actual type. She also uses Java 21 pattern-matching instanceof to handle a mixed event stream without casting.

โšก Dynamic dispatch โ€” one array, many types

The abstract keyword on Payment means you cannot instantiate it directly. Each concrete subclass must implement process(). Storing all subtypes in a Payment[] and calling p.process() in a loop is the canonical polymorphism pattern.

javac PolymorphBasics.java && java PolymorphBasics
PolymorphBasics.javaLesson 11 ยท abstract class + runtime dispatch
verified output
=== BoraPay โ€” Payment Processing Queue === UPI โ†’ P-1001 โ‚น2,500.00 via VPA arjun@sbi Receipt: P-1001 โ‚น2,500.00 [UpiPayment] CARD โ†’ P-1002 โ‚น18,000.00 card ending 4821 Receipt: P-1002 โ‚น18,000.00 [CardPayment] NETB โ†’ P-1003 โ‚น75,000.00 via SouthBank Receipt: P-1003 โ‚น75,000.00 [NetBankingPayment] UPI โ†’ P-1004 โ‚น500.00 via VPA priya@hdfc Receipt: P-1004 โ‚น500.00 [UpiPayment] Total processed: โ‚น96,000.00 (4 transactions)

๐Ÿ–จ๏ธ Overriding toString() โ€” portfolio display

Every Java class inherits toString() from Object. Overriding it means System.out.println(obj) automatically calls your version. FixedDeposit calls super.toString() to get the base format, then appends extra information โ€” a clean extension pattern.

javac OverrideDemo.java && java OverrideDemo
OverrideDemo.javaLesson 11 ยท overriding toString() for portfolio display
verified output
=== BoraPay โ€” Investment Portfolio === GOI-2034 face: โ‚น1,000,000.00 yield: 7.26% FD-8821 face: โ‚น500,000.00 yield: 7.10% (365 days) FD-8822 face: โ‚น250,000.00 yield: 3.58% (180 days) GOI-2029 face: โ‚น750,000.00 yield: 7.18%

๐Ÿ” Java 21 pattern-matching instanceof

Before Java 16, you'd write if (e instanceof PaymentEvent) { PaymentEvent pe = (PaymentEvent) e; ... } โ€” verbose and error-prone. Java 21 pattern-matching combines the check and cast into a single expression: if (e instanceof PaymentEvent pe). The variable pe is typed, already cast, and scoped to the if block.

javac InstanceofDemo.java && java InstanceofDemo
InstanceofDemo.javaLesson 11 ยท Java 21 pattern-matching instanceof
verified output
=== BoraPay โ€” Event Stream === LOGIN user=wanjiku ip=41.80.192.5 PAYMENT txn=P-5501 โ‚น8,500.00 ALERT account=NG-3301 reason=velocity breach PAYMENT txn=P-5502 โ‚น124,000.00 LOGIN user=chidi ip=197.210.44.2

๐Ÿ“‹ Quick reference โ€” polymorphism concepts

ConceptMeaning
PolymorphismOne type, many forms โ€” runtime dispatch to correct override
Dynamic dispatchJVM finds actual type at runtime, calls its method
abstract methodNo body in parent; subclass must override
abstract classCannot be instantiated; may have abstract and concrete methods
getClass().getSimpleName()Returns runtime class name (e.g. "UpiPayment")
Pattern-matching instanceofif (e instanceof PaymentEvent pe) โ€” auto-casts to pe
sealed class (Java 17+)Restricts which classes can extend it

๐ŸŽค Interview Q&A

EasyWhat is the difference between compile-time and runtime polymorphism?
+

Compile-time (static) polymorphism is method overloading โ€” the compiler picks the right method at compile time based on parameter types. Runtime (dynamic) polymorphism is method overriding โ€” the JVM picks the right method at runtime based on the actual object type. @Override is the key mechanism for runtime polymorphism.

EasyWhat happens if a concrete class doesn't implement all abstract methods?
+

It is a compile error. A class that extends an abstract class must either implement all abstract methods or itself be declared abstract. The compiler enforces this โ€” you cannot instantiate a class that leaves abstract methods unimplemented.

MediumWhat is the difference between an abstract class and an interface?
+

An abstract class can have constructors, instance fields, and a mix of abstract and concrete methods. A class can extend only one abstract class. An interface (pre-Java 8) could only have abstract methods; now it can also have default and static methods but no instance fields or constructors. A class can implement multiple interfaces. Use abstract classes for shared state; use interfaces for shared contracts.

MediumWhy is getClass().getSimpleName() preferred over instanceof chains for type inspection?
+

With getSimpleName() you get the runtime type name as a string, useful for logging. But for branching logic, pattern-matching instanceof is better โ€” it gives you a typed variable. A long instanceof chain (without sealed/switch) is a code smell suggesting the type hierarchy should carry the behaviour instead (polymorphism).

HardWhat is the Liskov Substitution Principle and how does it relate to @Override?
+

LSP (the L in SOLID) states that a subclass should be usable wherever its parent is expected, without breaking the program. When overriding, you should not narrow the method's preconditions or widen its postconditions. For example, overriding process() to throw an unchecked exception the parent never mentioned violates LSP because callers relying on Payment don't expect the exception. @Override ensures the signature matches but doesn't enforce LSP โ€” that's the developer's responsibility.

๐Ÿ“ Quiz โ€” 5 questions

Question 1 of 5
Payment p = new UpiPayment(...). What method runs when you call p.process()?
Question 2 of 5
What does abstract void process() mean?
Question 3 of 5
Java 21 pattern-matching instanceof โ€” if (e instanceof PaymentEvent pe) โ€” what is pe?
Question 4 of 5
Can you instantiate an abstract class directly with new Payment(...)?
Question 5 of 5
getClass().getSimpleName() on a UpiPayment object returns:
0
/ 5
Quiz complete!

Next: interfaces and abstract classes โ†’

โš ๏ธ Common mistakes

Expecting parent behaviour from an overridden call
This can't happen via runtime polymorphism. The JVM always calls the actual object's override. If you need the parent version inside the subclass, call super.process() explicitly. From outside, there is no way to bypass polymorphism.
Casting without instanceof check
(UpiPayment) p throws ClassCastException if p is actually a CardPayment. Always check instanceof before casting. Java 21 pattern-matching instanceof does both in one step and eliminates the risk.
Making abstract method private
Abstract methods must be overridable, so they can't be private. Use package-private, protected, or public. Trying to declare private abstract void process() is a compile error.
Forgetting @Override causes silent bugs
If you override tostring() instead of toString(), it compiles fine as a new method but System.out.println(obj) still calls Object's default. @Override catches the typo at compile time, turning an invisible bug into a clear error.

โœ… Key takeaways

  • Polymorphism: store subclass objects in a parent-type variable; Java dispatches to the correct override at runtime.
  • abstract methods have no body; every concrete subclass must provide one.
  • Always use @Override โ€” the compiler verifies the signature, catching silent bugs.
  • Java 21 pattern-matching instanceof eliminates manual casts and makes type-branching code safer.
  • Prefer pushing behaviour into overridden methods over long instanceof chains.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

From polymorphism to production Spring Boot

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’