Junior
What is polymorphism in programming?
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 simpler terms, the same method can behave differently depending on the object that calls it. This is achieved through inheritance and method overriding, as well as through the use of interfaces.
Example in Swift:
protocol Animal {
func makeSound()
}
class Dog: Animal {
func makeSound() {
print("Woof")
}
}
class Cat: Animal {
func makeSound() {
print("Meow")
}
}
func playSound(animal: Animal) {
animal.makeSound()
}
let dog = Dog()
let cat = Cat()
playSound(animal: dog) // Outputs: Woof
playSound(animal: cat) // Outputs: Meow
Here, the function playSound takes an object of type Animal, but depending on the specific class (Dog or Cat), the corresponding implementation of the makeSound method is called.