Junior — Middle
How can principles of polymorphism be applied to work with different object types?
sobes.tech AI
Answer from AI
Polymorphism allows working with objects of different classes through a common interface or base class, calling methods that are implemented differently in each class. This simplifies the code and increases its flexibility.
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
}
}
Here, a variable of type Animal can refer to objects of different classes, and the call to the sound() method will be executed according to the actual type of the object.