Polymorphism in Java with Examples
Polymorphism means 'many forms'. It allows one interface to be used for different data types or
actions.
Types of Polymorphism in Java:
1. Compile-time Polymorphism (Method Overloading)
2. Runtime Polymorphism (Method Overriding)
1. Compile-time Polymorphism (Method Overloading)
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator c = new Calculator();
System.out.println(c.add(2, 3)); // 5
System.out.println(c.add(2.5, 3.5)); // 6.0
}
}
2. Runtime Polymorphism (Method Overriding)
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
public static void main(String[] args) {
Animal a = new Dog(); // Parent class reference to child object
a.sound(); // Output: Dog barks
}
}