Junior — Middle
Why is it important to use polymorphism in Java?
sobes.tech AI
Answer from AI
Polymorphism in Java allows objects of different classes to be processed through a single interface or base class. This is important because:
- It increases flexibility and extensibility of the code — new classes can be added without modifying existing code.
- It simplifies maintenance and testing, as the code works with abstractions rather than specific implementations.
- It enables the use of dynamic method invocation (runtime polymorphism), making the program's behavior more adaptable.
Example:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() { System.out.println("Bark"); }
}
class Cat implements Animal {
public void sound() { System.out.println("Meow"); }
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog();
a.sound(); // Bark
a = new Cat();
a.sound(); // Meow
}
}