Junior — Middle
Explain the concept of polymorphism and how it is implemented in object-oriented programming languages.
sobes.tech AI
Answer from AI
Polymorphism is the ability of objects of different classes to respond to the same messages (method calls) in different ways. In object-oriented programming languages, this allows for using a single interface to work with different types of objects.
In Java, polymorphism is implemented through:
- Inheritance: subclasses inherit methods from the superclass.
- Method overriding: a subclass can change the behavior of a superclass method.
- References to base type: a variable of a base class can refer to an object of a subclass.
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"
}
}
Thus, polymorphism allows writing more flexible and extensible code, where behavior is determined at runtime depending on the actual object type.