Think of the word "run". A person runs, a program runs, a tap runs, a candidate runs for election. It's the same word, but what actually happens depends on who is doing it. Programming has the same idea: one method name, one call, different behaviour depending on the object. This is polymorphism, the fourth pillar of OOP, and arguably the one that makes the other three worthwhile.
In this chapter we'll look at both kinds of polymorphism (compile-time and run-time), see how a call is bound to the right method, learn upcasting and downcasting, and cover the subtle traps that interviewers like to ask about. The detailed rules of overloading and overriding are in the next chapter, Method Overloading vs Method Overriding.
What Is Polymorphism?
Polymorphism (Greek: "many forms") is the ability of a single interface, such as a method name, an operator or a reference variable, to work with values of different types, with the behaviour chosen according to the actual type involved.
The practical meaning: you can write code against a general type, and it automatically does the right thing for each specific type. Your code says "send this notification"; whether that becomes an email, an SMS or a push message is decided by the object.
Two Kinds of Polymorphism
Point | Compile-time polymorphism | Run-time polymorphism |
|---|---|---|
Also called | Static polymorphism, early binding | Dynamic polymorphism, late binding, dynamic method dispatch |
Achieved by | Method overloading, operator overloading (C++, Python), templates/generics | Method overriding through a parent-type reference |
Decided when | By the compiler, from the declared types of the arguments | While the program runs, from the actual class of the object |
Needs inheritance? | No | Yes (or interface implementation) |
Speed | No dispatch cost | A small lookup per call (usually negligible) |
A quick taste of compile-time polymorphism: Java's own System.out.println has separate versions for int, double, String, char[] and more. When you write println(5), the compiler picks the int version before the program ever runs. That's method overloading, which we cover in depth in the next chapter. The rest of this chapter focuses on run-time polymorphism, the kind that interviewers mean when they say "polymorphism".
Run-Time Polymorphism: A Complete Example
A college portal must notify students by email, SMS and push notification. Without polymorphism you'd write if (type.equals("SMS")) ... else if ... everywhere. With polymorphism:
import java.util.List;
abstract class Notification {
protected final String to;
Notification(String to) { this.to = to; }
abstract void send(String message);
}
class EmailNotification extends Notification {
EmailNotification(String to) { super(to); }
@Override
void send(String message) {
System.out.println("Email to " + to + ": " + message);
}
}
class SmsNotification extends Notification {
SmsNotification(String to) { super(to); }
@Override
void send(String message) {
// SMS is limited, so shorten long messages
String text = message.length() > 20 ? message.substring(0, 20) + "..." : message;
System.out.println("SMS to " + to + ": " + text);
}
}
class PushNotification extends Notification {
PushNotification(String to) { super(to); }
@Override
void send(String message) {
System.out.println("Push to device " + to + ": " + message);
}
}
public class NotifyDemo {
// One method handles every kind of notification
static void broadcast(List<Notification> channels, String message) {
for (Notification n : channels) {
n.send(message); // which send()? decided at run time
}
}
public static void main(String[] args) {
List<Notification> channels = List.of(
new EmailNotification("asha@example.com"),
new SmsNotification("+91-98xxxxxx10"),
new PushNotification("pixel-7a")
);
broadcast(channels, "Your exam results are now available");
}
}Output:
Email to asha@example.com: Your exam results are now available
SMS to +91-98xxxxxx10: Your exam results ar...
Push to device pixel-7a: Your exam results are now availableThe single line n.send(message) produced three different behaviours. And when the portal later adds WhatsApp, you write one new subclass; broadcast() stays exactly as it is. That's the payoff: code that is closed to modification but open to new types.
Run-time polymorphism needs three ingredients:
Inheritance (or interface implementation):
EmailNotification extends Notification.Overriding: each subclass provides its own
send().A parent-type reference to a child object:
Notification n = new EmailNotification(...).
Reference Type vs Object Type
Every polymorphism question becomes easy once you separate these two:
Notification n = new SmsNotification("+91...");
└────┬─────┘ └──────────┬───────────────┘
reference type object type
(compile time) (run time)
decides WHICH methods decides WHICH VERSION
you may call of an overridden method runsThe compiler only knows the reference type. It checks that
Notificationhas asend(String)method; otherwise the code doesn't compile.The JVM knows the real object. At run time it looks up the most specific override of
sendfor that object's class and calls it. This is called dynamic method dispatch.
How does the run-time lookup work?
Implementations typically give each class a method table (called a vtable in C++). Each overridable method has a fixed slot. A subclass's table copies the parent's entries and replaces the slots it overrides. Each object carries a hidden pointer to its class's table, so a call becomes "look up slot k in this object's table and jump there", a constant-time operation.
Notification table SmsNotification table
+---------------------+ +------------------------------+
| slot 0: send → none | | slot 0: send → Sms's send() |
| (abstract) | +------------------------------+
+---------------------+ ▲
|
SMS object: [ hidden pointer ]────────────┘
[ to = "+91..." ]The language standards don't require vtables, but this is how mainstream compilers and JVMs do it, and it's the expected answer in interviews.
Upcasting and Downcasting
Upcasting is treating a child object through a parent-type reference. It is automatic and always safe. Downcasting is converting a parent-type reference back to a child type. It needs an explicit cast and can fail at run time.
class Animal { void sound() { System.out.println("..."); } }
class Dog extends Animal {
@Override void sound() { System.out.println("Woof"); }
void fetch() { System.out.println("Dog fetches the ball"); }
}
class Cat extends Animal {
@Override void sound() { System.out.println("Meow"); }
}
public class CastDemo {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting: automatic and always safe
a.sound();
// a.fetch(); // compile error: Animal has no fetch()
if (a instanceof Dog d) { // pattern matching (Java 16+)
d.fetch(); // safe downcast
}
Animal b = new Cat();
Dog wrong = (Dog) b; // compiles, but fails at run time
}
}Output:
Woof
Dog fetches the ball
Exception in thread "main" java.lang.ClassCastException: class Cat cannot be cast to class Dog (Cat and Dog are in unnamed module of loader 'app')
at CastDemo.main(CastDemo.java:23)Key lessons:
a.fetch()fails at compile time even though the object really is a dog, because the reference typeAnimalhas nofetch().(Dog) bcompiles (aCatis anAnimal, and someAnimals areDogs), but the JVM checks the real object and throwsClassCastException.Always guard a downcast with
instanceof. Since Java 16 the pattern forma instanceof Dog dtests and casts in one step.If you find yourself downcasting a lot, the design is usually missing an overridable method in the parent.
What Is Not Polymorphic
Only overridable instance methods are dispatched at run time. Everything else is resolved from the reference type at compile time.
Fields are not polymorphic
class Parent {
String label = "parent field";
String show() { return "Parent.show()"; }
}
class Child extends Parent {
String label = "child field"; // hides, does NOT override
@Override String show() { return "Child.show()"; }
}
public class FieldDemo {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.label); // decided by REFERENCE type
System.out.println(p.show()); // decided by OBJECT type
}
}Output:
parent field
Child.show()The child object actually contains two label fields. Which one you see depends on the reference type. This is called field hiding, and it's a favourite trick question. (One more reason to keep fields private and expose them through methods.)
Static, private and final methods
static methods belong to the class, private methods are invisible to subclasses and final methods cannot be overridden, so none of them take part in run-time polymorphism. A static method with the same signature in a child hides the parent's one; the details are in Method Overloading vs Method Overriding.
A trap: calling an overridable method from a constructor
class Base {
Base() {
describe(); // calls an overridable method!
}
void describe() { System.out.println("Base"); }
}
class Derived extends Base {
private String name = "Derived"; // assigned AFTER Base() finishes
@Override
void describe() { System.out.println("name = " + name); }
}
public class CtorTrap {
public static void main(String[] args) {
new Derived();
}
}Output:
name = nullIn Java, dynamic dispatch works even during construction, so Base() calls Derived.describe(). But the Derived field initialisers haven't run yet (the parent is built first, as we saw in Inheritance), so name is still null. Never call overridable methods from a constructor. (C++ behaves differently: inside a base-class constructor, virtual calls go to the base version, because the derived part doesn't exist yet.)
Polymorphism in C++: the virtual Keyword
In Java every non-static, non-private, non-final method is overridable by default. In C++ you must opt in with virtual, and polymorphism works only through pointers or references.
#include <iostream>
class Animal {
public:
void eat() const { std::cout << "Animal eats\n"; } // NOT virtual
virtual void sound() const { std::cout << "Animal sound\n"; } // virtual
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void eat() const { std::cout << "Dog eats\n"; }
void sound() const override { std::cout << "Woof\n"; }
};
void byValue(Animal a) { a.sound(); } // copies only the Animal part!
int main() {
Dog d;
Animal& ref = d;
Animal* ptr = &d;
ref.eat(); // non-virtual: chosen by static type -> Animal
ref.sound(); // virtual: chosen by object type -> Dog
ptr->sound(); // same through a pointer -> Dog
byValue(d); // object slicing -> Animal
}Output:
Animal eats
Woof
Woof
Animal soundNon-virtual
eat()is bound at compile time from the declared type, soAnimal eatsis printed even though the object is aDog.Object slicing: passing a
Dogby value as anAnimalcopies only theAnimalpart. The result really is anAnimal, so the dog behaviour is lost. Pass polymorphic objects by reference or pointer.Write
overrideon overriding functions; the compiler then checks that you really are overriding something.
Operator Overloading
Operator overloading is a form of compile-time polymorphism: the same operator means different things for different types. + adds integers and joins strings even in Java, but Java doesn't let you define operators for your own classes. C++ and Python do:
#include <iostream>
class Money {
long paise;
public:
explicit Money(long p) : paise(p) {}
Money operator+(const Money& other) const { return Money(paise + other.paise); }
friend std::ostream& operator<<(std::ostream& os, const Money& m) {
return os << "Rs." << m.paise / 100 << '.' << (m.paise % 100 < 10 ? "0" : "") << m.paise % 100;
}
};
int main() {
Money fees(4999950), hostel(1500005);
std::cout << fees + hostel << '\n'; // calls fees.operator+(hostel)
}Output:
Rs.64999.55In Python the same is done with special methods such as __add__, shown below.
Polymorphism in Python: Duck Typing
Python doesn't check types at compile time. Any object with the right method works, related by inheritance or not: "if it walks like a duck and quacks like a duck, it's a duck".
class Email:
def send(self, msg):
print("Email:", msg)
class Pigeon: # not related to Email at all
def send(self, msg):
print("Pigeon carries:", msg)
class Money:
def __init__(self, paise):
self.paise = paise
def __add__(self, other): # operator overloading for +
return Money(self.paise + other.paise)
def __repr__(self):
return f"Rs.{self.paise / 100:.2f}"
for channel in (Email(), Pigeon()):
channel.send("Exam on Monday") # works for anything with send()
print(Money(4999950) + Money(1500005))
print(len("hello"), len([1, 2, 3]), len({"a": 1}))Output:
Email: Exam on Monday
Pigeon carries: Exam on Monday
Rs.64999.55
5 3 1Even built-in len() is polymorphic: it calls each object's own __len__.
Common Mistakes
Calling overloading "run-time polymorphism". Overloading is resolved by the compiler; only overriding through a parent reference is run-time.
Expecting fields or static methods to behave polymorphically. They are chosen by the reference type.
Downcasting without
instanceof, leading toClassCastException.Forgetting
virtualin C++, or passing objects by value and slicing them.Calling overridable methods from constructors, which can see uninitialised subclass fields in Java.
Long
if/elseorswitchchains on a "type" field. That's usually a sign that a polymorphic method is missing.
Interview and GATE-Style Questions
What is the difference between compile-time and run-time polymorphism?
Compile-time polymorphism (overloading, operator overloading) is resolved by the compiler from declared argument types. Run-time polymorphism (overriding) is resolved while the program runs, from the actual class of the object, through dynamic method dispatch on a parent-type reference.
Animal a = new Dog(); a.sound(); Which sound() runs, and why?
Dog's, if Dog overrides sound(). The compiler checks that Animal has sound(); at run time the JVM dispatches to the override for the actual object, which is a Dog.
Parent p = new Child(); both declare a field x. What does p.x give?
The parent's x. Fields are not overridden, only hidden, and field access is resolved from the reference type at compile time.
Can we achieve run-time polymorphism with data members?
No. Only overridable instance methods are dispatched dynamically. Data members are bound statically by the reference type.
What is a vtable?
A per-class table of pointers to the class's virtual functions. Each polymorphic object holds a hidden pointer (vptr) to its class's table, and a virtual call indexes into it to find the right override at run time. It's the usual implementation of dynamic dispatch in C++.
What is object slicing in C++?
When a derived object is copied into a base-class object (e.g. passed by value), only the base part is copied. The derived fields and overridden behaviour are lost. Use references or pointers to avoid it.
Does Java support operator overloading?
Not for user-defined types. The language itself overloads a few operators (e.g. + for numbers and string concatenation), but programmers cannot define new meanings for operators. C++ and Python allow it.
Summary
Polymorphism = one interface, many forms; the actual type decides the behaviour.
Compile-time (static, early binding): overloading, operator overloading. Run-time (dynamic, late binding): overriding + parent reference.
Reference type decides what you may call; object type decides which override runs.
Upcasting is automatic; downcasting needs a cast and an
instanceofcheck.Fields, static, private and final methods are not dynamically dispatched.
C++ needs
virtualand pointers/references; Python uses duck typing.
Overloading and overriding both "reuse a method name", which is why they're so often confused. The next chapter, Method Overloading vs Method Overriding, puts them side by side with their exact rules.