beginnerFree

Polymorphism

One supertype, many implementations

Polymorphism

Polymorphism lets you treat different objects uniformly through a shared type.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 1:16

The Big Picture

Polymorphism means "many forms" - one reference type can hold objects of different types. JVM picks the right method at runtime.

  • Compile-time type can differ from runtime type
  • Powers generic code: Collections.sort(List<T>)
  • Enables frameworks to call your overridden methods

The payoff for inheritance and interfaces.

How It Works

Java dispatches virtual calls on the object's runtime class, not the reference type (typically via a per-class method table).

  • Dynamic dispatch is cheap, near-constant overhead
  • JIT compiler inlines small methods for speed
  • final/static/private calls can be bound statically
  • Overloading: compile-time; overriding: runtime

In the Java Landscape

Polymorphism supports SOLID's Open/Closed Principle.

  • Overloading: same name, different params (compile-time)
  • Overriding: subclass replaces method (runtime)
  • Covariant returns (Java 5+) refine return types
  • Pattern matching (Java 16+) simplifies type checks
  • Visitor pattern leverages double dispatch

Pitfalls and Best Practices

  • Cast safely with instanceof before downcasting
  • Overloaded methods can confuse: remove(int) vs remove(Object)
  • Use @Override to catch signature typos
  • Can't override private, static, or final methods
  • Prefer interfaces for polymorphism over class hierarchies
#java#oop#polymorphism