๐ฏ 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
abstractmethods and abstract classes- Overriding
toString()for clean object printing - Java 21 pattern-matching
instanceofโ typed local variables without casting
๐ญ 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
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.
๐จ๏ธ 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.
๐ 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.
๐ Quick reference โ polymorphism concepts
| Concept | Meaning |
|---|---|
| Polymorphism | One type, many forms โ runtime dispatch to correct override |
| Dynamic dispatch | JVM finds actual type at runtime, calls its method |
abstract method | No body in parent; subclass must override |
abstract class | Cannot be instantiated; may have abstract and concrete methods |
getClass().getSimpleName() | Returns runtime class name (e.g. "UpiPayment") |
| Pattern-matching instanceof | if (e instanceof PaymentEvent pe) โ auto-casts to pe |
| sealed class (Java 17+) | Restricts which classes can extend it |
๐ค Interview Q&A
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.
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.
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.
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).
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
Payment p = new UpiPayment(...). What method runs when you call p.process()?abstract void process() mean?if (e instanceof PaymentEvent pe) โ what is pe?new Payment(...)?getClass().getSimpleName() on a UpiPayment object returns:Next: interfaces and abstract classes โ
โ ๏ธ Common mistakes
super.process() explicitly. From outside, there is no way to bypass polymorphism.(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.private. Use package-private, protected, or public. Trying to declare private abstract void process() is a compile error.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.
abstractmethods 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.
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 โ