What is Polymorphism?
Polymorphism means “many forms.”
In Java, it allows one object to take many forms — like a parent type being used to refer to child objects.
👉 It makes your code flexible, reusable, and extensible.
Types of Polymorphism
-
Compile-Time Polymorphism (Method Overloading)
-
Run-Time Polymorphism (Method Overriding)
1. Compile-Time Polymorphism – Method Overloading
Same method name, different parameters (in same class).
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
2. Run-Time Polymorphism – Method Overriding
A child class redefines a method from its parent.
Example:
class Animal {
void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
No comments:
Post a Comment