Polymorphism is one of the core concepts of object-oriented programming (OOP) in Java.
→ It allows objects to be treated as instances of their parent class rather than their actual class.
→ The word "polymorphism" is derived from the Greek words "poly" (meaning many) and "morph" (meaning form), signifying the ability to take many forms.
In Java, polymorphism is primarily achieved through method overriding and method overloading. It allows for flexibility and the ability to extend functionality by enabling objects to be manipulated regardless of their specific class types.
Compile-time Polymorphism (Static Polymorphism)
Example of Method Overloading:
class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Runtime Polymorphism (Dynamic Polymorphism)
Example of Method Overriding:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Outputs: Dog barks
}
}
+-------------------+
| MathOperations |
+-------------------+
| - add(int, int) |
| - add(double, double) |
+-------------------+
+-------------------+ +-------------------+
| Animal | | Dog |
+-------------------+ +-------------------+
| - sound() |<-- overridden -- | - sound() |
+-------------------+ +-------------------+