Introduction
- Poly means many and Morph means form.
- A method can behave differently in different situations.
- Examples:
- Person can be a father, husband, employee, etc
- Water can be liquid, solid or gas.
Types of Polymorphism -
- Compile Time / Static Polymorphism / Method Overloading
- Run Time / Dynamic Polymorphism / Method Overriding
Method Overloading: Multiple methods in the same class with the same name but different parameters. On the basis of RETURN TYPE overloading CAN’T be done.
public class MathOperations {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Method Overriding: A method in a subclass has the same name, return type, and parameters as a method in the parent class.
public class Animal {
void sound() {
System.out.println("This is a generic sound.");
}
}
public class Cat extends Animal {
void sound() {
System.out.println("The cat meows.");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Cat();
animal.sound(); // Outputs: The cat meows.
}
}