On Day 24, we learn about Polymorphism, one of the four main pillars of OOP. In Java, polymorphism allows the same method to perform different actions depending on the object that calls it. The most common form of polymorphism is method overriding.
1. What is Method Overriding?
Method overriding occurs when a subclass provides its own implementation of a method already defined in its superclass. The method must have the same name, return type, and parameters.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog(); // polymorphism
Animal a2 = new Cat();
a1.sound(); // calls Dog's version
a2.sound(); // calls Cat's version
}
}
Explanation: Even though a1
and a2
are declared as Animal
, the actual method called depends on the object type (Dog
or Cat
).
2. Why Use Polymorphism?
- Allows flexible and reusable code.
- Enables writing general methods for parent classes while letting subclasses define specific behavior.
- Makes code more extensible (easily add new subclasses).
3. The super Keyword
If we want to call the parent class version of an overridden method, we use super
.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
super.sound(); // call parent version
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
Explanation: Here, Dog
first calls the Animal
sound and then adds its own behavior.
Summary
Polymorphism means "many forms". Method overriding is a key example in Java where the subclass provides its own version of a method. Using polymorphism, one interface (like sound()
) can have different implementations depending on the object type.