Junior — Middle
Can you explain the principle of polymorphism in Java and its application?
sobes.tech AI
Answer from AI
Polymorphism in Java is the ability of objects of different classes to respond to the same method calls in different ways. It allows using a single interface to work with different types of objects.
Application:
- Enables writing flexible and extensible code.
- Used in method overriding in subclasses (runtime polymorphism).
- Allows working with objects through references of the base class or interface.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal a1 = new Dog();
Animal a2 = new Cat();
a1.sound(); // Outputs "Bark"
a2.sound(); // Outputs "Meow"
}
}
Here, the sound() method is called on objects of different classes, but the behavior depends on the specific type of the object.