9.2.1. Inheritance
One of the most critical capabilities that a class has but a struct doesn't have is inheritance. Inheritance is the ability of a class to inherit the properties of another existing class and add more functionalities along with it. In other words, we can build a new class based on another existing class. For example, we can build a new class Car based on the Vehicle class we have:
//The Vehicle class....
class Vehicle{
var type:String
init(type:String){
self.type = type
}
}
// defining a new class inheriting Vehicle class
class Car:Vehicle{
var make:String
var model:String
init(type:String, make:String, model:String) {
//initializing this instance's properties...
self.make = make
self.model = model
//Calling super class's initializer...
super.init(type: type)
}
}Here, we are doing a few things:
Using
:we are saying thatCarinherits properties from an existing classVehicle. In this case,Vehicleis the super class ofCar.We added two properties
makeandmodelinCarclass. Hence, we now have three properties inCarclass:type(inherited fromVehicle),make, andmodel.We need to write our own
init()method for each class we write. So,CarandVehicleboth have their own initializers. Think about the initializer of classCar. TheCarclass has it's own properties, so we need to initialize them. Also, we need to initialize the super classVehicleinsideCar's initializer. That is what we are doing in theinit()function insideCar. We usesuperkeyword is used to access the super classVehicle's properties.
Overriding methods
Let's define a method describe() inside the class Vehicle which prints a string.
Now, let's create an instance of the Car class, and call describe() method it inherited from Vehicle.
The thing is, it still just prints, "This is a Car." However, we have more information in class Car, like the make and model of the instance. What if we want to print more information?
We can override the method we inherited from the super class Vehicle. For example,
It prints:
This is called method overriding. A class not only can inherit a method from the superclass but also can change (override) it.
Source code
Last updated
Was this helpful?