๐ 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
Compile-time (Static) Polymorphism
Achieved via method overloading โ same method name with different parameters.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