π What is Polymorphism?
Polymorphism means βmany forms.β
In Java, polymorphism allows the same method name to behave differently based on the situation.
π― Types of Polymorphism in Java
Java supports two types:
- Compile-time Polymorphism (Method Overloading)
- Runtime Polymorphism (Method Overriding)
1οΈβ£ Compile-Time Polymorphism (Method Overloading)
- Same method name
- Different parameters
- Decision made at compile time
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(5, 3));
System.out.println(c.add(2.5, 3.5));
}
}
2οΈβ£ Runtime Polymorphism (Method Overriding)
- Same method name
- Same parameters
- Different implementation in child class
- Decision happens at runtime.
Example:
class Animal {
void sound() {
System.out.println("Animal makes 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 a;
a = new Dog();
a.sound();
a = new Cat();
a.sound();
}
}
Top comments (0)