Lesson 22: OOP Pillar 3: Polymorphism
Polymorphism means "many forms." In Java, it allows us to treat objects of different classes in a uniform way, as long as those classes share a common parent or interface.
1. Compile-Time Polymorphism (Method Overloading)
This is achieved by having multiple methods within the same class that share the same name but have different signatures (different number or types of parameters).
java public class Calculator { // Method 1: adds two integers public int add(int a, int b) { return a + b; }
// Method 2: adds three integers (overloaded)
public int add(int a, int b, int c) { return a + b + c; }
// Method 3: adds two doubles (overloaded by type)
public double add(double a, double b) { return a + b; }
}
During compilation, the compiler determines which method to call based on the arguments provided.
2. Runtime Polymorphism (Method Overriding)
This is the core of dynamic dispatch. It occurs when an object is referred to by a reference variable of its parent class, and the method being called is an overridden method.
Key Concept: The method executed is determined by the actual object type (runtime object), not the reference type.
java public class Vehicle { public void move() { System.out.println("Vehicle moves."); } } public class Truck extends Vehicle { @Override public void move() { System.out.println("Truck rumbles down the road."); } } public class Bicycle extends Vehicle { @Override public void move() { System.out.println("Bicycle pedals quietly."); } }
// Runtime Polymorphism in action: Vehicle v1 = new Truck(); // Reference type is Vehicle, Object type is Truck Vehicle v2 = new Bicycle();
v1.move(); // Calls Truck's move() v2.move(); // Calls Bicycle's move()
Polymorphism is essential for writing flexible, extensible code, especially when working with collections of diverse but related objects.