Junior — Middle
How can object behavior management be implemented through polymorphism in code?
sobes.tech AI
Answer from AI
Polymorphism in Java allows objects of different classes to respond differently to the same method calls, which is convenient for managing object behavior.
To implement behavior management through polymorphism, a base interface or abstract class with a defined method is usually created, and then different subclasses implement this method in their own way.
Example:
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
class Cat implements Animal {
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal[] animals = {new Dog(), new Cat()};
for (Animal animal : animals) {
animal.makeSound(); // Method call depends on the specific object
}
}
}
Thus, behavior management of objects reduces to calling a single method, and the specific implementation is determined by the object type at runtime. This simplifies code extension and maintenance.