๐Ÿ” Polymorphism

Polymorphism allows one interface to be used for different underlying forms (data types). It enables the same method name to behave differently depending on the context โ€” improving flexibility and maintainability.


๐ŸŽฏ Types of Polymorphism in Java

  1. Compile-time (Static) Polymorphism
    Achieved via method overloading โ€” same method name with different parameters.

  2. Runtime (Dynamic) Polymorphism
    Achieved via method overriding โ€” subclass provides a specific implementation of a method defined in its superclass.


๐Ÿงช Java Example: Compile-time

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

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

๐Ÿงช Java Example: Runtime

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

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

public class Main {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.makeSound();  // Output: Bark (runtime polymorphism)
    }
}

โœ… Advantages

  • Flexible and extensible code
  • Supports dynamic method resolution
  • Key to achieving loose coupling in OOP