Polymorphism means one interface or method name can have multiple forms of behaviour.
Two types:
Compile-time polymorphism: Method overloading.
Runtime polymorphism: Method overriding.
What is method overloading?
Multiple methods have the same name but different parameter lists.
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}What is method overriding?
A child class provides its own implementation of a method inherited from its parent class.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}Overloading vs overriding?
Overloading | Overriding |
|---|---|
Same method name | Same method signature |
Different parameters | Same parameters |
Usually same class | Parent-child relationship |
Compile-time polymorphism | Runtime polymorphism |