What is Polymorphism?
Polymorphism ka matlab hota hai "bahuroopiya" — yani kisi ek cheez ka kai roop hona. Java me ye object-oriented programming ka ek mool tatva hai jisme ek method ya object alag alag tarike se behave kar sakta hai.
1. Compile-Time Polymorphism (Static Polymorphism)
Compile-time polymorphism method overloading ke zariye achieve hota hai. Ek hi class me multiple methods same naam ke lekin alag parameters ke saath hote hain. Compiler decide karta hai konsa method call karna hai.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 10)); // Output: 15
System.out.println(calc.add(5, 10, 15)); // Output: 30
System.out.println(calc.add(3.5, 2.7)); // Output: 6.2
}
}
2. Runtime Polymorphism (Dynamic Polymorphism)
Runtime polymorphism method overriding ke dwara hota hai. Subclass parent class ke method ko override karta hai aur run-time mein actual object ke type ke hisaab se method call hota hai.
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.makeSound(); // Output: Dog barks
a = new Cat();
a.makeSound(); // Output: Cat meows
}
}
Key Differences Between Compile-Time and Runtime Polymorphism
Aspect | Compile-Time Polymorphism | Runtime Polymorphism |
---|---|---|
Also Known As | Static Binding | Dynamic Binding |
Achieved By | Method Overloading | Method Overriding |
Binding Time | Compile Time | Run Time |
Performance | Faster | Relatively Slower |
Flexibility | Less Flexible | More Flexible |