Java Polymorphism
1. Definition:
Polymorphism in Java means "one interface, multiple methods." It allows objects to be treated as
instances of their parent class rather than their actual class. Polymorphism is a core concept of
Object-Oriented Programming (OOP).
2. Types of Polymorphism:
- Compile-time (Method Overloading):
- Same method name, different parameters in the same class.
- Example:
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
- Runtime (Method Overriding):
- Subclass provides a specific implementation of a method defined in the parent class.
- Example:
class Animal {
void sound() { [Link]("Animal makes sound"); }
}
class Dog extends Animal {
void sound() { [Link]("Dog barks"); }
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog();
[Link](); // Output: Dog barks
}
}
3. Advantages:
- Code reusability
- Flexibility in code
- Easier maintenance
4. Key Points:
- Compile-time polymorphism uses overloading.
- Runtime polymorphism uses overriding.
- Achieved using inheritance and interfaces.