Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class to inherit properties and methods from another class. This promotes code reuse and establishes a natural hierarchy between classes.

Key Concepts

  1. Base Class (Superclass): The class whose properties and methods are inherited.
  2. Derived Class (Subclass): The class that inherits from the base class.
  3. Overriding: The ability of a subclass to provide a specific implementation of a method that is already defined in its superclass.
  4. Super Keyword: Used to call the superclass's methods and properties from the subclass.

Syntax

In Swift, inheritance is implemented using the class keyword. A subclass is defined by specifying the superclass after a colon.

class Animal {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func makeSound() {
        print("Some generic sound")
    }
}

class Dog: Animal {
    var breed: String
    
    init(name: String, breed: String) {
        self.breed = breed
        super.init(name: name)
    }
    
    override func makeSound() {
        print("Bark")
    }
}

Explanation

  • Base Class (Animal):

    • name: A property to store the name of the animal.
    • init(name:): An initializer to set the name.
    • makeSound(): A method to print a generic sound.
  • Derived Class (Dog):

    • breed: A property to store the breed of the dog.
    • init(name:breed:): An initializer to set the name and breed. It calls the superclass initializer using super.init(name:).
    • override func makeSound(): Overrides the makeSound method to print "Bark".

Practical Example

Let's create a more detailed example to understand inheritance better.

class Vehicle {
    var currentSpeed = 0.0
    
    var description: String {
        return "Traveling at \(currentSpeed) miles per hour"
    }
    
    func makeNoise() {
        // Do nothing - an arbitrary vehicle doesn't necessarily make a noise
    }
}

class Bicycle: Vehicle {
    var hasBasket = false
    
    override func makeNoise() {
        print("Ring ring")
    }
}

class Car: Vehicle {
    var gear = 1
    
    override var description: String {
        return super.description + " in gear \(gear)"
    }
}

Explanation

  • Base Class (Vehicle):

    • currentSpeed: A property to store the speed of the vehicle.
    • description: A computed property to describe the vehicle.
    • makeNoise(): A method that does nothing by default.
  • Derived Class (Bicycle):

    • hasBasket: A property to indicate if the bicycle has a basket.
    • override func makeNoise(): Overrides the makeNoise method to print "Ring ring".
  • Derived Class (Car):

    • gear: A property to store the current gear of the car.
    • override var description: Overrides the description property to include the gear information.

Exercises

Exercise 1: Create a Subclass

Create a subclass ElectricCar that inherits from Car and adds a property batteryLevel.

class ElectricCar: Car {
    var batteryLevel: Int
    
    init(batteryLevel: Int, currentSpeed: Double, gear: Int) {
        self.batteryLevel = batteryLevel
        super.init()
        self.currentSpeed = currentSpeed
        self.gear = gear
    }
    
    override var description: String {
        return super.description + " with battery level at \(batteryLevel)%"
    }
}

Solution Explanation

  • ElectricCar:
    • batteryLevel: A property to store the battery level.
    • init(batteryLevel:currentSpeed:gear:): An initializer to set the battery level, current speed, and gear. It calls the superclass initializer using super.init().
    • override var description: Overrides the description property to include the battery level information.

Exercise 2: Override a Method

Override the makeNoise method in the ElectricCar class to print "Whirr".

class ElectricCar: Car {
    var batteryLevel: Int
    
    init(batteryLevel: Int, currentSpeed: Double, gear: Int) {
        self.batteryLevel = batteryLevel
        super.init()
        self.currentSpeed = currentSpeed
        self.gear = gear
    }
    
    override var description: String {
        return super.description + " with battery level at \(batteryLevel)%"
    }
    
    override func makeNoise() {
        print("Whirr")
    }
}

Solution Explanation

  • ElectricCar:
    • override func makeNoise(): Overrides the makeNoise method to print "Whirr".

Common Mistakes

  1. Forgetting to Call Superclass Initializer: Always call the superclass initializer when initializing a subclass.
  2. Incorrect Method Overriding: Ensure the method signature in the subclass matches the superclass method exactly.
  3. Accessing Superclass Properties: Use the super keyword to access properties and methods from the superclass.

Conclusion

Inheritance allows you to create a new class based on an existing class, promoting code reuse and establishing a clear hierarchy. By understanding and utilizing inheritance, you can create more organized and maintainable code. In the next section, we will explore polymorphism, which builds on the concepts of inheritance to allow objects to be treated as instances of their superclass.

© Copyright 2024. All rights reserved