Swift Inheritance

Swift Inheritance

Inheritance is a fundamental concept in Object-Oriented Programming.

It allows one class to inherit the characteristics (properties and methods) of another class.

The class that inherits is called the Subclass (or child class).

The class being inherited from is called the Superclass (or parent class).


Defining a Base Class

Any class that does not inherit from another class is known as a base class.

In Swift, classes do not inherit from a universal base class by default (unlike Object in Java).

Creating a Base Class:

class Vehicle {
    var currentSpeed = 0.0
    func makeNoise() {
        // Vehicles don't inherently make a specific noise
    }
}

Creating a Subclass

To subclass another class, write the subclass name, followed by a colon, followed by the superclass name.

The subclass automatically gains all the properties and methods of its superclass.

Subclassing Example:

class Vehicle {
    var currentSpeed = 0.0
    func makeNoise() {
        // Vehicles don't inherently make a specific noise
    }
}

class Bicycle: Vehicle { var hasBasket = false }

let myBike = Bicycle() myBike.currentSpeed = 15.0 // Inherited from Vehicle! print("Bicycle speed: \(myBike.currentSpeed)")


Overriding Methods

A subclass can provide its own custom implementation of an instance method it inherited.

This is known as overriding.

To override a method, you must prefix the function definition with the override keyword.

Overriding a Method:

class Vehicle {
    var currentSpeed = 0.0
    func makeNoise() {
        // Vehicles don't inherently make a specific noise
    }
}

class Train: Vehicle { override func makeNoise() { print("Choo Choo!") } }

let myTrain = Train() myTrain.makeNoise()

Using the override keyword is mandatory; if you forget it, the compiler will throw an error, preventing accidental overrides.


Preventing Overrides with final

Sometimes you want to completely prevent a class from being subclassed, or a method from being overridden.

You can do this by marking the class or method with the final keyword.

Writing final class Vehicle ensures that no other class can inherit from it, which makes your code safer and slightly faster!


Exercise

Which keyword must you use to provide a custom implementation of an inherited method?