- Prerequisites
- 6.1 Inheritance · 6.2 Method Overriding · 4.4 Methods (overloading)
- Covers
- Compile-time polymorphism · Runtime polymorphism · Dynamic method dispatch · Upcasting · Downcasting
- Related
- 7.1 Interfaces · 7.4 Interface-Based Design · 2.5 Control Flow (pattern matching) · Book 5 Vol IV (Strategy, State)
On this page
1Concept / Definition
Polymorphism — "many forms" — means one piece of code can work with values of different types, and each type can respond in its own way. In Java the phrase usually means run-time polymorphism: a call such as shape.area() executes Circle.area() or Rectangle.area() depending on the actual object. Overloading is sometimes called compile-time polymorphism, because the compiler chooses among several methods with the same name.


2Why It Exists
Without polymorphism, code that handles several kinds of object must check the kind and branch: if (s is a Circle) … else if (s is a Rectangle) …. Every new kind means finding and editing every such branch. With polymorphism, each type carries its own behaviour, and client code simply calls the method. New types can be added without changing existing clients — the Open/Closed Principle (Book 5).

3Core Concepts
Compile-time polymorphism
Also called static polymorphism: several methods share a name but differ in parameter types, and the compiler selects one from the static types of the arguments (4.4). The decision is fixed in the bytecode and never changes at run time. Generics are sometimes also described as compile-time (parametric) polymorphism: one List<T> implementation works for many element types.
Runtime polymorphism
Also called dynamic polymorphism: an instance method call through a reference of a supertype runs the implementation belonging to the object's actual class. It requires inheritance or interface implementation plus overriding. The compiler checks only that the method exists on the static type; the JVM chooses the implementation.

Dynamic method dispatch
Dynamic dispatch is the mechanism behind run-time polymorphism. Every object's header identifies its class; each class has a method table (a vtable, and itables for interfaces) mapping each overridable method to the implementation that applies to that class. A virtual call looks up the method in the table of the receiver's class and jumps to it.

Only instance methods are dispatched dynamically. Static methods, private methods, constructors and field accesses are resolved statically. A field with the same name in a subclass hides the parent's field, and which one is read depends on the reference type — one more reason to keep fields private.
Upcasting
Converting a subtype reference to a supertype reference: Shape s = new Circle(2);. It is implicit and always safe, because a Circle is a Shape. After upcasting, the compiler allows only the supertype's methods through s, but calls still dispatch to Circle's overrides. Upcasting is what lets collections, method parameters and fields be declared with general types.
Downcasting
Converting a supertype reference to a subtype reference: Circle c = (Circle) s;. It requires an explicit cast because it may be wrong; the JVM checks the object's class at run time and throws ClassCastException if it is not compatible. Since Java 16, pattern matching (if (s instanceof Circle c)) combines the test and the cast safely.

4How It Works Internally
The compiler emits invokevirtual for class methods and invokeinterface for interface methods; both carry a symbolic reference to the method as declared on the static type. At run time HotSpot uses the receiver's method table to find the actual implementation.
The JIT then optimises aggressively using profiling (1.2). If a call site has only ever seen one receiver class (monomorphic), it inlines that implementation with a cheap type guard. With two classes (bimorphic) it inlines both. With many (megamorphic) it falls back to a table lookup and cannot inline. If a new class appears at a monomorphic site, the JIT deoptimises and recompiles. The practical conclusion: polymorphism is usually free, except at very hot call sites that see many different types.
5APIs / Features / Syntax
// Upcast (implicit)
Shape s = new Circle(2.0);
// Old-style downcast
if (s instanceof Circle) {
Circle c = (Circle) s;
System.out.println(c.radius());
}
// Pattern matching (Java 16+)
if (s instanceof Circle c && c.radius() > 1) {
System.out.println(c.radius());
}
// Exhaustive switch over a sealed interface (Java 21+)
double perimeter = switch (s) {
case Circle c -> 2 * Math.PI * c.radius();
case Rectangle r -> 2 * (r.width() + r.height());
case Triangle t -> t.a() + t.b() + t.c();
};6Practical Examples
Example 1 — Polymorphic pricing
public interface DiscountPolicy {
Money apply(Money price, Customer customer);
}
public final class NoDiscount implements DiscountPolicy {
public Money apply(Money price, Customer c) { return price; }
}
public final class PercentageDiscount implements DiscountPolicy {
private final int percent;
public PercentageDiscount(int percent) { this.percent = percent; }
public Money apply(Money price, Customer c) { return price.percentOff(percent); }
}
public final class LoyaltyDiscount implements DiscountPolicy {
public Money apply(Money price, Customer c) {
return c.years() >= 5 ? price.percentOff(10) : price;
}
}
public class Checkout {
private final DiscountPolicy policy; // any implementation
public Checkout(DiscountPolicy policy) { this.policy = policy; }
public Money total(Cart cart, Customer c) {
return policy.apply(cart.subtotal(), c); // dynamic dispatch
}
}Example 2 — Mini program: polymorphic pricing, complete and running
Problem. Example 1 shows the shape of the design but leaves out Money, Cart and Customer. This program supplies them as small records and runs one Checkout class with four policies, the last one added later as a lambda, without changing Checkout.
public class PricingDemo {
record Money(BigDecimal amount) {
Money { amount = amount.setScale(2, RoundingMode.HALF_EVEN); }
static Money of(String v) { return new Money(new BigDecimal(v)); }
Money percentOff(int p) {
return new Money(amount.multiply(BigDecimal.valueOf(100 - p))
.divide(BigDecimal.valueOf(100)));
}
@Override public String toString() { return amount.toPlainString(); }
}
record Customer(String name, int years) {}
record Cart(List<Money> prices) {
Money subtotal() {
return new Money(prices.stream().map(Money::amount)
.reduce(BigDecimal.ZERO, BigDecimal::add));
}
}
interface DiscountPolicy { Money apply(Money price, Customer c); }
static final class NoDiscount implements DiscountPolicy {
public Money apply(Money price, Customer c) { return price; }
}
static final class PercentageDiscount implements DiscountPolicy {
private final int percent;
PercentageDiscount(int percent) { this.percent = percent; }
public Money apply(Money price, Customer c) {
return price.percentOff(percent);
}
}
static final class LoyaltyDiscount implements DiscountPolicy {
public Money apply(Money price, Customer c) {
return c.years() >= 5 ? price.percentOff(10) : price;
}
}
static final class Checkout {
private final DiscountPolicy policy; // any implementation
Checkout(DiscountPolicy policy) { this.policy = policy; }
Money total(Cart cart, Customer c) {
return policy.apply(cart.subtotal(), c); // dynamic dispatch
}
}
public static void main(String[] args) {
Cart cart = new Cart(List.of(Money.of("1200"), Money.of("299.50")));
Customer asha = new Customer("asha", 7), ravi = new Customer("ravi", 1);
Map<String, DiscountPolicy> policies = new LinkedHashMap<>();
policies.put("NoDiscount", new NoDiscount());
policies.put("PercentageDiscount(15)", new PercentageDiscount(15));
policies.put("LoyaltyDiscount", new LoyaltyDiscount());
policies.put("lambda: 100 off over 1000", (price, c) -> // added later
price.amount().compareTo(new BigDecimal("1000")) > 0
? new Money(price.amount().subtract(new BigDecimal("100")))
: price);
for (var entry : policies.entrySet()) {
Checkout checkout = new Checkout(entry.getValue()); // unchanged
System.out.println(entry.getKey() + ": asha "
+ checkout.total(cart, asha)
+ ", ravi " + checkout.total(cart, ravi));
}
}
}NoDiscount: asha 1499.50, ravi 1499.50
PercentageDiscount(15): asha 1274.58, ravi 1274.58
LoyaltyDiscount: asha 1349.55, ravi 1499.50
lambda: 100 off over 1000: asha 1399.50, ravi 1399.50Why it behaves this way. Checkout.total contains one call, policy.apply(...), compiled against the interface. Which apply runs is decided for each object at run time, so the same line gives four different results. LoyaltyDiscount is the only policy that looks at the customer, which is why only its line differs between asha, with seven years, and ravi, with one. DiscountPolicy has a single abstract method, so a lambda is just another implementation: new behaviour arrives as a new object, never as an edit to Checkout. 15% off 1,499.50 is 1,274.575, which HALF_EVEN rounds to 1,274.58.
Example 3 — Overloading versus overriding in one program
class Printer {
void print(Shape s) { System.out.println("shape: " + s.area()); }
void print(Circle c) { System.out.println("circle: " + c.area()); }
}
Shape s = new Circle(1);
new Printer().print(s); // "shape: 3.14…"
// Overload chosen at COMPILE time from the static type Shape;
// inside it, s.area() is dispatched at RUN time to Circle.area().Example 4 — Fields are not polymorphic
class A { String name = "A"; String name() { return name; } }
class B extends A { String name = "B"; @Override String name() { return name; } }
A x = new B();
System.out.println(x.name); // "A" — field chosen by reference type
System.out.println(x.name()); // "B" — method dispatched on objectExample 5 — Two axes of change: polymorphic methods versus an exhaustive switch
Problem. The Architect's view in section 9 says to choose between polymorphism and pattern matching by the axis of change. This program shows both styles: shapes that carry their own behaviour, and order events that are a sealed set handled by switches.
public class TwoAxes {
// Axis 1: behaviour inside the types - adding a type is local
interface Shape { double area(); String describe(); }
record Circle(double r) implements Shape {
public double area() { return Math.PI * r * r; }
public String describe() { return "circle r=" + r; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
public String describe() { return "square side=" + side; }
}
// Axis 2: a sealed set of types - adding an operation is local
sealed interface Event permits Paid, Shipped, Refunded {}
record Paid(long paise) implements Event {}
record Shipped(String carrier) implements Event {}
record Refunded(long paise) implements Event {}
static String audit(Event e) { // operation 1
return switch (e) {
case Paid p -> "paid " + p.paise() / 100.0;
case Shipped s -> "shipped via " + s.carrier();
case Refunded r -> "refunded " + r.paise() / 100.0;
};
}
static long cashEffect(Event e) { // operation 2, added later
return switch (e) {
case Paid p -> p.paise();
case Shipped s -> 0;
case Refunded r -> -r.paise();
};
}
public static void main(String[] args) {
for (Shape s : new Shape[] {new Circle(1), new Square(2)})
System.out.println(s.describe() + " -> "
+ String.format(Locale.ROOT, "%.2f", s.area()));
long net = 0;
Event[] events = {new Paid(49_900), new Shipped("road"),
new Refunded(9_900)};
for (Event e : events) {
System.out.println(audit(e));
net += cashEffect(e);
}
System.out.println("net paise " + net);
}
}circle r=1.0 -> 3.14
square side=2.0 -> 4.00
paid 499.0
shipped via road
refunded 99.0
net paise 40000
Why it behaves this way. A new Shape class needs no change anywhere else, because each shape brings its own area and describe; a new operation on shapes, however, means editing every class. The events are the opposite: cashEffect was added as one new method without touching the records, and because Event is sealed and the switches have no default, adding a fourth event type would make both switches fail to compile until they handle it (Figure 7). String.format uses Locale.ROOT so that the decimal point does not depend on the machine.
Example 6 — Double dispatch: making an overload follow the run-time type
Problem. Example 3 shows that an overload is chosen from the static type. When the operation really must depend on the run-time type of an argument, and adding a method to the type hierarchy is not an option, the Visitor pattern gets there with two virtual calls.
public class DoubleDispatch {
interface Shape { <R> R accept(Visitor<R> v); }
record Circle(double r) implements Shape {
public <R> R accept(Visitor<R> v) { return v.visit(this); } // Circle
}
record Square(double side) implements Shape {
public <R> R accept(Visitor<R> v) { return v.visit(this); } // Square
}
interface Visitor<R> { R visit(Circle c); R visit(Square s); }
static final class Exporter implements Visitor<String> {
public String visit(Circle c) { return "<circle r='" + c.r() + "'/>"; }
public String visit(Square s) { return "<rect w='" + s.side() + "'/>"; }
String visit(Shape s) { return "<unknown/>"; } // the trap
}
public static void main(String[] args) {
Exporter ex = new Exporter();
List<Shape> shapes = List.of(new Circle(1.5), new Square(2));
for (Shape s : shapes)
System.out.println("overload only: " + ex.visit(s));
for (Shape s : shapes)
System.out.println("visitor: " + s.accept(ex));
}
}overload only: <unknown/>
overload only: <unknown/>
visitor: <circle r='1.5'/>
visitor: <rect w='2.0'/>
Why it behaves this way. In the first loop s has the static type Shape, so javac picks visit(Shape) for both objects, whatever they are. In the second loop s.accept(ex) is a virtual call that runs Circle.accept or Square.accept; inside it, this has the precise static type, so v.visit(this) is compiled against visit(Circle) or visit(Square), and that call is dispatched on the visitor (Figure 8). In modern Java, a sealed hierarchy with a pattern-matching switch (Example 5) is often the simpler way to get the same result.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| instanceof chains to decide behaviour | Every new type edits many places | Polymorphic method, or sealed types + exhaustive switch |
| Unchecked downcasts | ClassCastException in production | Pattern matching; redesign the API |
| Expecting overloads to dispatch on run-time type | Wrong method chosen | Use overriding (or the Visitor pattern) for run-time choice |
| Hidden fields with the same name in subclasses | Value depends on reference type | Private fields, accessor methods |
| Overrides that break the supertype's contract | Polymorphic callers fail unpredictably | Honour LSP (6.4); contract tests |
| Casting to an implementation class to reach extra methods | The caller depends on one implementation, and the cast fails when another, or a proxy, is injected | Add the operation to the interface, or depend on the specific type openly |
| A default branch in a switch over a sealed type | A new subtype falls silently into default instead of failing to compile | Leave out default so the compiler checks every case (Example 5) |
8Performance & Production Considerations
- Virtual and interface calls are usually inlined by the JIT; there is no need to avoid polymorphism for performance in ordinary code.
- Megamorphic call sites in very hot loops (for example, a generic event handler seeing dozens of event types) can be measurably slower. Profile before optimising; if needed, split call sites by type or use a switch over a sealed type.
- Class hierarchy analysis lets the JIT treat a method as effectively final while only one implementation is loaded; loading plugins later can trigger deoptimisation, visible as brief slowdowns.
9Architecture & Design Considerations
Polymorphism is the mechanism behind most extensibility in software architecture:
- Strategy, State, Command and Template Method patterns (Book 5) are structured uses of polymorphism.
- Dependency injection relies on it: a service depends on an interface, and the container supplies the implementation.
- Plugins and SPIs (
ServiceLoader, JDBC drivers, logging back ends) are polymorphism across library boundaries. - Ports and adapters: the domain calls interfaces; infrastructure provides polymorphic implementations.
10Interview Questions & Answers
What is polymorphism in Java?
The ability of one piece of code to work with objects of different types, each responding in its own way. Run-time polymorphism comes from overriding and dynamic dispatch; compile-time polymorphism from overloading (and, broadly, generics).
What is the difference between upcasting and downcasting?
Upcasting converts a subtype reference to a supertype reference; it is implicit and always safe. Downcasting converts a supertype reference to a subtype; it needs an explicit cast and is checked at run time, throwing ClassCastException if the object is not of that type.
What is dynamic method dispatch?
The run-time selection of an overridden method's implementation based on the actual class of the receiving object, not the declared type of the reference. HotSpot implements it with per-class method tables, heavily optimised by the JIT.
Are fields and static methods polymorphic?
No. Fields and static methods are resolved at compile time from the reference's declared type; a same-named field or static method in a subclass hides, rather than overrides, the parent's.
Given void print(Shape s) and void print(Circle c), which runs for Shape s = new Circle(); print(s);?
print(Shape). Overload selection happens at compile time using the static type Shape. Only method calls on s inside print are dispatched on the run-time type. Example 6 shows how to make the choice follow the run-time type when it must.
How does pattern matching change downcasting?
if (obj instanceof Circle c) tests the type and binds a correctly typed variable in one step, removing the separate unchecked cast and its ClassCastException risk. With sealed types, switch patterns can also be checked for exhaustiveness.
Is polymorphism slow?
Usually not. The JIT inlines monomorphic and bimorphic call sites using type profiles, so they cost about the same as direct calls. Only megamorphic sites in hot code pay for a table lookup and lose inlining; this is rarely significant and should be confirmed by profiling.
Why is a long instanceof chain considered a smell, and when is it acceptable?
It centralises knowledge of every subtype in the client, so adding a type requires finding and editing every chain, and missing one fails silently. It is acceptable when replaced by an exhaustive switch over a sealed hierarchy, where the compiler flags missing cases.
How does polymorphism enable dependency injection and testability?
Components depend on interfaces; the container injects a concrete implementation at run time. Tests inject fakes or mocks implementing the same interface. The component's code is unchanged in both cases because calls dispatch polymorphically.
How would you design an extension mechanism so other teams can add payment methods without changing the core?
Define a small PaymentMethod interface (or SPI) with a clear contract, discover implementations through dependency injection or ServiceLoader, route requests by a key each implementation declares, and provide contract tests every implementation must pass. The core calls the interface polymorphically and never references concrete implementations.
When would you deliberately choose a sealed hierarchy with switches over open polymorphism in a system design?
When the set of variants is a stable business fact — payment types, order states, event kinds in a closed domain — and many independent operations (pricing, reporting, validation) need to handle all of them. Exhaustive switches then give compile-time assurance that each operation covers every variant. For open-ended plugin ecosystems, open polymorphism is the better fit.
What does this program print?
public class PolyQuiz {
static class Animal {
String name = "animal";
String sound() { return "..."; }
static String kind() { return "Animal"; }
}
static class Dog extends Animal {
String name = "dog";
@Override String sound() { return "woof"; }
static String kind() { return "Dog"; }
}
static String describe(Animal a) { return "animal:" + a.sound(); }
static String describe(Dog d) { return "dog:" + d.sound(); }
@SuppressWarnings("static")
public static void main(String[] args) {
Animal a = new Dog();
System.out.println(a.name + " " + a.sound() + " " + a.kind() + " "
+ describe(a));
}
}It prints animal woof Animal animal:woof. Only sound() is chosen from the object, a Dog. The field a.name is read from the declared type Animal, the static method a.kind() is bound to Animal.kind() at compile time, and the overload describe(Animal) is chosen from the static type of a; inside it, a.sound() is dispatched again and gives "woof". Four expressions, and only the two instance-method calls depend on the run-time type.
How does the Visitor pattern make an operation depend on the run-time types of two objects?
Java dispatches dynamically only on the receiver of a call. The Visitor uses two calls: shape.accept(v) dispatches on the shape, and inside accept the call v.visit(this) is compiled against the overload for that concrete class, because this has the precise static type there, and is then dispatched on the visitor. The result is chosen by both run-time types, at the cost of an accept method in every class and a visit overload per class in every visitor (Example 6).
After a release that added several new event handler plugins, throughput of the event pipeline drops by 15%, although each handler is fast. What could explain it, and how do you check?
The pipeline's central call, handler.handle(event), used to see one or two handler classes, so the JIT inlined them; with many classes the call site has become megamorphic and every call goes through a table lookup without inlining, which also blocks optimisations around it. Confirm it with a profiler or JFR, which show the call as a hot non-inlined frame, and compare against the previous release. If it is the cause, split the call site by type, for example one loop per handler group, or route through a switch over a sealed event type; measure again before keeping the change.
Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.
Key Takeaways
- Overloading is chosen at compile time; overriding is dispatched at run time.
- Dynamic dispatch uses the object's class; fields and statics are resolved by reference type.
- Upcasts are implicit and safe; downcasts are checked — prefer pattern matching.
- The JIT makes polymorphism almost free except at megamorphic hot spots.
- Polymorphism underpins DI, patterns, plugins and ports-and-adapters.