Lesson 14 of 25

Polymorphism

Runtime Polymorphism

Polymorphism means 'many forms.' A parent reference can hold a child object, and the correct method is called at runtime.

Example
Shape shape1 = new Circle(5);
Shape shape2 = new Rectangle(4, 6);

// The correct area() method is called based on actual type
System.out.println(shape1.area()); // 78.54 (Circle)
System.out.println(shape2.area()); // 24.0 (Rectangle)

// Array of mixed shapes
Shape[] shapes = {
    new Circle(3),
    new Rectangle(5, 2),
    new Circle(7)
};

for (Shape s : shapes) {
    System.out.printf("Area: %.2f%n", s.area());
}

// instanceof check
if (shape1 instanceof Circle c) {  // Java 16+
    System.out.println("Radius: " + c);
}