Dynamic binding (also known as late binding) is a concept in programming where the method or function to be executed is determined at runtime rather than at compile time. This allows for more flexible and extensible code, particularly in object-oriented programming, where it enables polymorphism.
class Animal {
func makeSound() {
print("Some generic animal sound")
}
}
class Dog: Animal {
override func makeSound() {
print("Bark")
}
}
class Cat: Animal {
override func makeSound() {
print("Meow")
}
}
func printAnimalSound(animal: Animal) {
animal.makeSound()
}
let myDog = Dog()
let myCat = Cat()
printAnimalSound(animal: myDog) // Output: Bark
printAnimalSound(animal: myCat) // Output: Meow
How It Works:
class Animal {
func makeSound() {
print("Some generic animal sound")
}
}
class Dog: Animal {
override func makeSound() {
print("Bark")
}
}
func printAnimalSound(animal: Animal) {
animal.makeSound() // Message passing
}
let myDog = Dog()
printAnimalSound(animal: myDog) // Output: Bark