Junior — Middle
Explain the concept of polymorphism in object-oriented programming and how it is implemented in code.
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming is the ability of objects of different classes to respond to the same messages (method calls) in different ways. This allows using a single interface to work with different types of objects.
In Java, polymorphism is implemented through inheritance and method overriding. For example, a base class declares a method, and subclasses implement it in their own way.
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, a variable of type Animal can refer to objects of different subclasses, and the call to the sound() method will be executed depending on the actual type of the object — this is polymorphism.