Polymorphism allows a single reference type to represent objects of different subclasses and invoke behavior specific to each object at runtime. This enables developers to write flexible and extensible code where common operations can be performed through a shared interface or parent class while allowing each subclass to provide its own implementation.
Key Points: • Runtime polymorphism is achieved through method overriding, where subclasses provide their own implementation of a parent class method. • The client code interacts with the parent type, making it easy to add new subclasses without changing existing logic. • Polymorphism promotes loose coupling, extensibility, and adherence to the Open/Closed Principle.
Example: In an animal management system, all animals can perform a speak() action. However, a Dog barks, a Cat meows, and a Bird chirps. Using polymorphism, the same method call produces different behavior depending on the actual object type.
Code Example:
class Animal {
public void speak() {
System.out.println(
"Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println(
"Dog barks");
}
}
class Cat extends Animal {
@Override
public void speak() {
System.out.println(
"Cat meows");
}
}
class Bird extends Animal {
@Override
public void speak() {
System.out.println(
"Bird chirps");
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = {
new Dog(),
new Cat(),
new Bird()
};
for (Animal animal : animals) {
animal.speak();
}
}
}Interview Tip: A concise interview answer is: Polymorphism allows a parent class reference to refer to different subclass objects and invoke their overridden methods at runtime. This enables different animal behaviors such as barking, meowing, and chirping through a common Animal reference, making the code more flexible and extensible.