Junior — Middle
What is the purpose and advantages of using polymorphism in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism is a principle of object-oriented programming that allows objects of different classes to have the same interface but different implementations of methods.
Advantages of polymorphism:
- Flexibility and extensibility of code: you can write general code that works with the base type, and specific behavior is determined in subclasses.
- Simplification of maintenance and modification: adding new types does not require changing existing code.
- Improved readability and reusability: a common interface makes it easier to understand and use classes.
Example in Swift:
class Animal {
func sound() {
print("Some sound")
}
}
class Dog: Animal {
override func sound() {
print("Bark")
}
}
class Cat: Animal {
override func sound() {
print("Meow")
}
}
let animals: [Animal] = [Dog(), Cat()]
for animal in animals {
animal.sound() // Calls the appropriate method in each subclass
}