In Java, Polymorphism allows us to treat different objects as if they are the same "type" (usually their parent type), but when we call a method, Java is smart enough to run the specific version of that method belonging to the child class.
Two Types of Polymorphism
Method Overriding (Runtime): A child class provides a specific implementation of a method that is already defined in its parent class.
Method Overloading (Compile-time): When a class has multiple methods with the same name but different parameters (e.g.,
add(int a, int b)andadd(double a, double b)).
The Code Example:
// Parent Class
class Animal {
void makeSound() {
System.out.println("The animal makes a generic sound.");
}
}
// Child Class 1
class Dog extends Animal {
@Override // This tells Java we are replacing the parent's method
void makeSound() {
System.out.println("The dog says: Woof Woof!");
}
}
// Child Class 2
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("The cat says: Meow!");
}
}
public class Main {
public static void main(String[] args) {
// Here is the magic: Polymorphic Reference
// We create a list of 'Animals' but fill it with a Dog and a Cat
Animal myDog = new Dog();
Animal myCat = new Cat();
// Even though both are stored in 'Animal' variables,
// they behave according to their real identity!
myDog.makeSound();
myCat.makeSound();
System.out.println("---");
// Example of Method Overloading (same name, different inputs)
System.out.println("Math result 1: " + multiply(5, 5));
System.out.println("Math result 2: " + multiply(2.5, 4.0));
}
// Overloaded methods
public static int multiply(int a, int b) { return a * b; }
public static double multiply(double a, double b) { return a * b; }
}Expected Output:
The dog says: Woof Woof!
The cat says: Meow!
---
Math result 1: 25
Math result 2: 10.0