Welcome to the exciting world of Swift Inheritance! Today, we'll explore this powerful feature that enables code reusability and class hierarchy. Let's dive in! š
Inheritance is a mechanism that allows one class (called the subclass or derived class) to acquire the properties and methods of another class (called the superclass or base class). This way, we can create a new class that extends an existing one, saving us from writing redundant code.
š” Pro Tip: Inheritance is a cornerstone of object-oriented programming (OOP) and makes code more modular, maintainable, and extensible.
Let's create a simple superclass called Animal:
class Animal {
var name: String
var legs: Int
init(name: String, legs: Int) {
self.name = name
self.legs = legs
}
func walk() {
print("\(name) is walking on its \(legs) legs.")
}
}In this example, we've created a Animal class with a name and legs property, an initializer to set these properties, and a walk() method.
Now, let's create a subclass called Dog that inherits from Animal:
class Dog: Animal {
var breed: String
init(name: String, legs: Int, breed: String) {
self.breed = breed
super.init(name: name, legs: legs)
}
}Here, we've defined a Dog class that inherits from Animal. We've added a new breed property and an initializer that takes three arguments. Note that we call super.init() to initialize the properties of the superclass.
Now, we can create an instance of Dog and call its methods:
let myDog = Dog(name: "Fido", legs: 4, breed: "Labrador")
myDog.walk() // "Fido is walking on its 4 legs."That's it! We've successfully created a subclass that inherits from a superclass in Swift. Let's reinforce our understanding with a quiz:
What does inheritance allow a class to do?
Happy coding! š