Swift Inheritance

Building classes that inherit properties and methods from other classes

๐Ÿงฌ What is Inheritance?

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


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

// Inherited class (subclass)
class Dog: Animal {
    override func makeSound() {
        print("Woof! Woof!")
    }
}

let myDog = Dog(name: "Buddy")
myDog.makeSound() // Output: "Woof! Woof!"
                                    

Output:

Woof! Woof!

Key Inheritance Concepts

๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ

Superclass

The parent class that provides properties and methods

class Vehicle {
    var speed: Int = 0
}
๐Ÿ‘ถ

Subclass

The child class that inherits from superclass

class Car: Vehicle {
    var brand: String = ""
}
๐Ÿ”„

Override

Modify inherited methods in subclass

override func start() {
    print("Car started")
}
โฌ†๏ธ

Super

Call superclass methods from subclass

override func start() {
    super.start()
}

๐Ÿ”น Basic Inheritance Example

Here's how to create a simple inheritance hierarchy:

// Superclass
class Shape {
    var color: String
    
    init(color: String) {
        self.color = color
    }
    
    func describe() {
        print("This is a \(color) shape")
    }
}

// Subclass
class Circle: Shape {
    var radius: Double
    
    init(color: String, radius: Double) {
        self.radius = radius
        super.init(color: color)
    }
    
    override func describe() {
        print("This is a \(color) circle with radius \(radius)")
    }
}

let myCircle = Circle(color: "red", radius: 5.0)
myCircle.describe()

Output:

This is a red circle with radius 5.0

๐Ÿ”น Method Overriding

Subclasses can override methods from their superclass:

class Bird {
    func fly() {
        print("Bird is flying")
    }
}

class Eagle: Bird {
    override func fly() {
        print("Eagle soars high in the sky")
    }
}

class Penguin: Bird {
    override func fly() {
        print("Penguins can't fly, but they swim!")
    }
}

let eagle = Eagle()
let penguin = Penguin()

eagle.fly()    // Eagle soars high in the sky
penguin.fly()  // Penguins can't fly, but they swim!

Output:

Eagle soars high in the sky

Penguins can't fly, but they swim!

๐Ÿง  Test Your Knowledge

What keyword is used to inherit from a class in Swift?