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 that Car inherits properties from an existing class Vehicle. In this case, Vehicle is the super class of Car.

  • We added two properties make and model in Car class. Hence, we now have three properties in Car class: type (inherited from Vehicle), make, and model.

  • We need to write our own init() method for each class we write. So, Car and Vehicle both have their own initializers. Think about the initializer of class Car. The Car class has it's own properties, so we need to initialize them. Also, we need to initialize the super class Vehicle inside Car's initializer. That is what we are doing in the init() function inside Car. We use super keyword is used to access the super class Vehicle'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?