Eroxl's Notes
Polymorphism

Polymorphism is the ability of different types of objects to respond to the same method call in different ways. In object-oriented programming, polymorphism allows a single interface to represent different underlying forms (data types).

Types of Polymorphism

Subtype Polymorphism (Runtime Polymorphism)

The most common form in OOP, where a variable of a parent type can refer to objects of any subtype, and method calls are dispatched to the appropriate implementation based on the object's actual type at runtime.

class Animal {
    void makeSound() { System.out.println("Some sound"); }
}

class Dog extends Animal {
    void makeSound() { System.out.println("Bark"); }
}

class Cat extends Animal {
    void makeSound() { System.out.println("Meow"); }
}

Animal a = new Dog();
a.makeSound();  // Prints "Bark" (not "Some sound")

Polymorphic Dispatch

Polymorphic dispatch (also called dynamic dispatch) is the mechanism that determines which method implementation to call at runtime:

  1. The variable has a static apparent type (e.g., Animal)
  2. The object has a dynamic actual type (e.g., Dog)
  3. The actual type must be a subtype of the apparent type
  4. Method calls invoke the actual type's implementation