Sobes.tech
Junior

Tell us about the inheritance chain of classes in the Swift programming language.

sobes.tech AI

Answer from AI

Classes in Swift support single inheritance. Each class inherits from one parent class, forming a hierarchy. The inheritance chain starts with a base class that inherits from nothing and extends downward through child classes.

Inheritance properties:

  • Overriding: A child class can override the implementation of methods, properties, and subscripts of the parent class. The keyword override is used.
  • Preventing Overrides: You can prevent a member from being overridden by marking it with the keyword final. The entire class can also be declared as final.
  • Access to the parent class: A child class can access the implemented members of the parent class using the keyword super. This is useful for calling the parent method's implementation or accessing the parent property.

Example:

// Base class
class Vehicle {
    var currentSpeed = 0.0

    func makeNoise() {
        // Empty implementation
    }
}

// Child class inheriting from Vehicle
class Car: Vehicle {
    var numberOfDoors = 4

    // Overriding the makeNoise method
    override func makeNoise() {
        print("Beep beep")
    }
}

// Child class inheriting from Car
class ElectricCar: Car {
    var batteryLevel = 100.0

    // Adding a new property
    let isElectric = true

    // Overriding the property from the base class
    override internal var currentSpeed: Double {
        didSet {
            if currentSpeed > 0 {
                print("Electric car is moving")
            }
        }
    }
}

In this example:

  • Vehicle is the base class.
  • Car inherits from Vehicle. It adds the property numberOfDoors and overrides the makeNoise method.
  • ElectricCar inherits from Car. It adds the property batteryLevel, the constant isElectric, and overrides the currentSpeed property.

Inheritance chain: Vehicle -> Car -> ElectricCar. Each class in this chain has access to all open (or accessible in another context) members of the classes higher in the hierarchy.