Junior — Middle
Can you explain the concept of inheritance in object-oriented programming?
sobes.tech AI
Answer from AI
Inheritance is a mechanism of object-oriented programming that allows creating a new class based on an existing one. The new class (child) inherits all properties and methods of the base class, and can add its own or override inherited ones.
This allows:
- Reusing code
- Creating class hierarchies
- Ensuring polymorphism
Example in Swift:
class Animal {
func sound() {
print("Some sound")
}
}
class Dog: Animal {
override func sound() {
print("Bark")
}
}
let dog = Dog()
dog.sound() // Outputs "Bark"
Here, the Dog class inherits from Animal and overrides the sound method.