Junior — Middle
Can you list the different types of polymorphism in object-oriented programming?
sobes.tech AI
Answer from AI
In object-oriented programming, several types of polymorphism are distinguished:
-
Subtype Polymorphism — the most common type, implemented through inheritance and method overriding. It allows objects of different classes, related by hierarchy, to use the same interface.
-
Parametric Polymorphism — implemented through generics, where functions or classes work with any data types, regardless of the specific type.
-
Ad hoc Polymorphism — achieved through method or operator overloading, where one function has multiple implementations with different parameters.
Example in Java with subtype polymorphism:
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 myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Bark
myCat.sound(); // Meow
}
}