✓✓Polymorphism means “many forms”.
✓✓In OOP, it allows one entity (method or object) to perform different tasks in different scenarios.
🔹 Types of Polymorphism in Java:
- Compile-time Polymorphism (Method Overloading)
✓✓Same method name but different parameter list.
✓✓Decided at compile time.
- Runtime Polymorphism (Method Overriding)
✓✓Same method name, same parameters, but defined in parent and child classes.
✓✓Decided at runtime using dynamic method dispatch. at runtime using dynamic method dispatch.
Program
Method Overloading (Compile-time)
class Calculator {
// Method with 2 parameters
int add(int a, int b) {
return a + b;
}
// Method with 3 parameters
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("Sum of 2 numbers: " + calc.add(10, 20));
System.out.println("Sum of 3 numbers: " + calc.add(10, 20, 30));
}
}
🔹 Output:
Sum of 2 numbers: 30
Sum of 3 numbers: 60
Example 2: Method Overriding (Runtime Polymorphism)
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Animal();
a1 = newDog();
a1.sound();
a1 = newCat();
a1.sound();
}
}
🔹 Output:
Dog barks
Cat meows
Top comments (0)