Java Polymorphism
Polymorphism means "many forms". In Java it describes the ability to treat objects of different classes through a common parent type, while each object still behaves according to its own class. You write code once against the parent type, and it works for every subclass — including ones that don't exist yet.
One variable type, many object types
A variable of a superclass type can refer to an object of any of its subclasses. When you call an overridden method, Java looks at the actual object at runtime to decide which version to run. This is called dynamic dispatch.
class Animal {
String sound() {
return "...";
}
}
class Dog extends Animal {
@Override
String sound() { return "Woof"; }
}
class Cat extends Animal {
@Override
String sound() { return "Meow"; }
}
class Cow extends Animal {
@Override
String sound() { return "Moo"; }
}
class Main {
public static void main(String[] args) {
Animal[] farm = { new Dog(), new Cat(), new Cow(), new Animal() };
for (Animal a : farm) {
System.out.println(a.getClass().getSimpleName() + ": " + a.sound());
}
}
}Dog: Woof
Cat: Meow
Cow: Moo
Animal: ...
The loop only knows about Animal, yet each object answers in its own way.
Why it matters
Polymorphism removes long if/switch chains on "what type is this?". Here a payroll method handles every kind of employee without knowing the details:
class Employee {
protected final String name;
Employee(String name) { this.name = name; }
double monthlyPay() { return 0; }
}
class Salaried extends Employee {
private final double yearly;
Salaried(String name, double yearly) { super(name); this.yearly = yearly; }
@Override double monthlyPay() { return yearly / 12; }
}
class Hourly extends Employee {
private final double rate;
private final int hours;
Hourly(String name, double rate, int hours) { super(name); this.rate = rate; this.hours = hours; }
@Override double monthlyPay() { return rate * hours; }
}
class Contractor extends Employee {
private final double invoice;
Contractor(String name, double invoice) { super(name); this.invoice = invoice; }
@Override double monthlyPay() { return invoice; }
}
class Main {
static double runPayroll(Employee[] staff) {
double total = 0;
for (Employee e : staff) {
System.out.printf("%-6s %8.2f%n", e.name, e.monthlyPay());
total += e.monthlyPay();
}
return total;
}
public static void main(String[] args) {
Employee[] staff = {
new Salaried("Ana", 54000),
new Hourly("Ben", 22.5, 120),
new Contractor("Chen", 3100)
};
System.out.printf("Total %8.2f%n", runPayroll(staff));
}
}Ana 4500.00
Ben 2700.00
Chen 3100.00
Total 10300.00
Adding a new Intern class later requires no change to runPayroll.
What the compiler sees vs. what runs
The declared type of a variable decides which methods you're allowed to call. The runtime type of the object decides which implementation runs:
Animal a = new Dog();
a.sound(); // OK: Animal declares sound(); Dog's version runs
a.fetch(); // error: Animal has no method fetch()Casting and instanceof
To use subclass-specific methods, check the type with instanceof and cast. Modern Java combines both in one step with a pattern variable:
class Animal {
String name() { return "animal"; }
}
class Dog extends Animal {
@Override String name() { return "dog"; }
void fetch() { System.out.println("The dog fetches the ball"); }
}
class Bird extends Animal {
@Override String name() { return "bird"; }
void fly() { System.out.println("The bird flies away"); }
}
class Main {
public static void main(String[] args) {
Animal[] pets = { new Dog(), new Bird() };
for (Animal a : pets) {
if (a instanceof Dog d) { // test and cast in one step
d.fetch();
} else if (a instanceof Bird b) {
b.fly();
}
}
Animal x = new Bird();
try {
Dog wrong = (Dog) x; // old-style cast - fails at runtime
} catch (ClassCastException e) {
System.out.println("Cannot treat a " + x.name() + " as a dog");
}
}
}The dog fetches the ball
The bird flies away
Cannot treat a bird as a dog
Tip: If you find yourself writing many
instanceofchecks, it's often a sign that the behaviour belongs in an overridden method instead.
Compile-time vs. runtime polymorphism
| Compile-time (static) | Runtime (dynamic) | |
|---|---|---|
| Mechanism | method overloading | method overriding |
| Decided by | the compiler, from argument types | the JVM, from the object's class |
| Example | print(int) vs. print(String) |
Dog.sound() vs. Cat.sound() |
When people say "polymorphism" in Java they usually mean the runtime kind.
Test yourself
Given Animal a = new Cat(); and Cat overrides sound(), which version does a.sound() run?
- Animal's
- Cat's
- Both
- Compile error
With Animal a = new Dog();, why can't you call a.fetch() if only Dog declares fetch?
- fetch is private
- The declared type Animal has no fetch method
- Dogs can't fetch
- It works fine
What does if (obj instanceof String s) do?
- Converts obj to a String
- Tests the type and binds a casted variable s if it matches
- Creates a new String
- Always returns true