Polymorphism

One interface, multiple implementations

Polymorphism

Polymorphism means 'many forms'. It allows objects of different types to be treated through a common interface. There are two main types: compile-time (method overloading) and runtime (method overriding).

Compile-time Polymorphism (Method Overloading)

java
// Method Overloading
public class Calculator {
    // Same method name, different parameters
    public int add(int a, int b) {
        return a + b;
    }

    public double add(double a, double b) {
        return a + b;
    }

    public int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
calc.add(1, 2);        // calls add(int, int)
calc.add(1.5, 2.5);    // calls add(double, double)
calc.add(1, 2, 3);     // calls add(int, int, int)

Runtime Polymorphism (Method Overriding)

java
// Runtime Polymorphism
abstract class Shape {
    abstract double area();
    abstract double perimeter();

    public void display() {
        System.out.printf("Area: %.2f, Perimeter: %.2f%n",
            area(), perimeter());
    }
}

class Circle extends Shape {
    private double radius;

    Circle(double radius) { this.radius = radius; }

    @Override
    double area() { return Math.PI * radius * radius; }

    @Override
    double perimeter() { return 2 * Math.PI * radius; }
}

class Rectangle extends Shape {
    private double width, height;

    Rectangle(double w, double h) { width = w; height = h; }

    @Override
    double area() { return width * height; }

    @Override
    double perimeter() { return 2 * (width + height); }
}

// Polymorphic usage — same interface, different behavior
Shape[] shapes = { new Circle(5), new Rectangle(4, 6) };
for (Shape s : shapes) {
    s.display(); // calls the correct overridden method
}

💬 What is the difference between overloading and overriding?

Overloading (compile-time): Same method name, different parameter lists, in the same class. Resolved at compile time. Overriding (runtime): Same method signature in parent and child classes. Resolved at runtime based on actual object type. Overriding requires inheritance; overloading does not.