Polymorphism

Polymorphism allows one method to have different implementations based on the object that calls it. It can happen at compile-time or runtime.

// Method Overloading (Compile-time Polymorphism)


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

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

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(10, 20));   // Output: 30
        System.out.println(calc.add(10, 20, 30)); // Output: 60
    }
}
// Method Overriding (Runtime Polymorphism)


class Animal {
    public void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.sound(); // Output: Dog barks
    }
}

Polymorphism — Structure map

Clickable & Draggable!

Polymorphism — Related pages: