Lesson 63Classes

Inheritance

What is Inheritance?

Inheritance allows a class to inherit properties and methods from another class. The inheriting class is called a subclass, and the class it inherits from is the superclass.

Inheritance Syntax

class Subclass: Superclass {
    // Additional properties and methods
}

Key Concepts

super

Access superclass methods and initializers

Inherited Members

Subclass gets all parent properties/methods

Multi-level

Classes can inherit from subclasses

final

Prevent a class from being inherited

Initializer Rules

  • Initialize your own properties first
  • Then call super.init()
  • Subclass must call a designated initializer of superclass
main.swift
// INHERITANCE
// Classes can inherit properties and methods from other classes

// BASE CLASS (Parent/Superclass)
class Animal {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    func makeSound() {
        print("Some sound")
    }

    func describe() {
        print("\(name) is \(age) years old")
    }
}

// SUBCLASS (Child class)
class Dog: Animal {
    var breed: String

    init(name: String, age: Int, breed: String) {
        self.breed = breed
        super.init(name: name, age: age)  // Call parent init
    }

    func fetch() {
        print("\(name) is fetching the ball!")
    }
}

let buddy = Dog(name: "Buddy", age: 3, breed: "Golden Retriever")
buddy.describe()    // Inherited method
buddy.makeSound()   // Inherited method
buddy.fetch()       // Dog's own method

// ANOTHER SUBCLASS
class Cat: Animal {
    var isIndoor: Bool

    init(name: String, age: Int, isIndoor: Bool) {
        self.isIndoor = isIndoor
        super.init(name: name, age: age)
    }

    func purr() {
        print("\(name) is purring...")
    }
}

let whiskers = Cat(name: "Whiskers", age: 2, isIndoor: true)
whiskers.describe()  // Inherited
whiskers.purr()      // Cat's own method

// MULTI-LEVEL INHERITANCE
class Vehicle {
    var brand: String
    var year: Int

    init(brand: String, year: Int) {
        self.brand = brand
        self.year = year
    }

    func start() {
        print("Vehicle starting...")
    }
}

class Car: Vehicle {
    var numberOfDoors: Int

    init(brand: String, year: Int, doors: Int) {
        self.numberOfDoors = doors
        super.init(brand: brand, year: year)
    }

    func honk() {
        print("Beep beep!")
    }
}

class ElectricCar: Car {
    var batteryCapacity: Int  // kWh

    init(brand: String, year: Int, doors: Int, battery: Int) {
        self.batteryCapacity = battery
        super.init(brand: brand, year: year, doors: doors)
    }

    func charge() {
        print("Charging \(batteryCapacity)kWh battery...")
    }
}

let tesla = ElectricCar(brand: "Tesla", year: 2023, doors: 4, battery: 75)
tesla.start()   // From Vehicle
tesla.honk()    // From Car
tesla.charge()  // From ElectricCar

// PREVENTING INHERITANCE WITH final
final class SecureData {
    var data: String

    init(data: String) {
        self.data = data
    }
}

// class HackedData: SecureData { }  // ERROR: Cannot inherit from final class

Try It Yourself!

Create a Shape base class with area() method. Then create Rectangle and Circle subclasses!