Polymorphism Basics

One interface, multiple implementations

Interview Relevant: Core OOP principle
5 min read

Polymorphism in Java

Polymorphism means "many forms". A single interface or parent class reference can represent multiple child class objects.

Key Idea: Same method call → different behavior at runtime.

Code Examples

One interface, multiple implementations

java
1
2interface Payment {
3    void pay();
4}
5
6class CreditCardPayment implements Payment {
7    public void pay() {
8        System.out.println("Paid using Credit Card");
9    }
10}
11
12class UpiPayment implements Payment {
13    public void pay() {
14        System.out.println("Paid using UPI");
15    }
16}
17
18Payment p1 = new CreditCardPayment();
19Payment p2 = new UpiPayment();
20
21p1.pay();
22p2.pay();
23          

Use Cases

  • Loose coupling
  • Plug-and-play implementations
  • Framework abstractions
  • Strategy pattern

Common Mistakes to Avoid

  • Using concrete classes instead of interfaces
  • Expecting compile-time behavior
  • Overusing instanceof