Junior
What problem does polymorphism solve in programming?
sobes.tech AI
Answer from AI
Polymorphism allows objects of different classes to respond to the same message (method call) differently, depending on their actual type. This increases the flexibility and extensibility of the code.
Main advantages:
- Versatility: You can work with a collection of objects of different types through a common interface or base class.
- Extensibility: Easily add new classes that implement the same interface without changing existing code.
- Simplification of code: Reduces the number of conditional operators (
if/else if) for handling different object types.
Example:
// Base class
class Animal {
public void makeSound() {
System.out.println("Makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark!");
}
}
// Subclass
class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow!");
}
}
public class Main {
public static void main(String[] args) {
// Array of objects of different types, but with a common reference to the base class
Animal[] animals = new Animal[2];
animals[0] = new Dog();
animals[1] = new Cat();
// Single method call, reaction depends on the actual object type
for (Animal animal : animals) {
animal.makeSound();
}
}
}