Swift Inheritance and Overriding Example

1. Introduction

Inheritance is a fundamental concept in object-oriented programming where a new class inherits properties and behaviors from another class. The class that gets inherited is called the superclass, and the class that inherits is called the subclass. In Swift, a class can inherit from another class, allowing it to adopt the superclass's properties, methods, and other characteristics. One of the significant advantages of inheritance is code reuse.

When a subclass inherits methods from its superclass, it has an option to override the inherited method to provide its custom implementation. This is called method overriding.

2. Source Code Example

// Define a base class
class Animal {
    func sound() -> String {
        return "Some generic animal sound"
    }
}

// Define a subclass
class Dog: Animal {
    // Overriding the sound() method of the superclass
    override func sound() -> String {
        return "Bark"
    }
}

// Define another subclass
class Cat: Animal {
    // Overriding the sound() method of the superclass
    override func sound() -> String {
        return "Meow"
    }
}

// Create instances
let genericAnimal = Animal()
print("Generic animal makes: \(genericAnimal.sound())")

let dog = Dog()
print("Dog goes: \(dog.sound())")

let cat = Cat()
print("Cat goes: \(cat.sound())")

Output:

Generic animal makes: Some generic animal sound
Dog goes: Bark
Cat goes: Meow

3. Step By Step Explanation

1. We define a base class Animal which has a method sound(). This method returns a generic animal sound.

2. The Dog class inherits from Animal. This means Dog has access to the sound() method from Animal. But, to provide a dog-specific sound, we override the sound() method in the Dog class.

3. Similarly, the Cat class also inherits from Animal and overrides the sound() method to return a cat-specific sound.

4. We create instances of the Animal, Dog, and Cat classes.

5. When we invoke the sound() method on these instances, each instance returns the sound according to its class definition. The generic animal gives a generic sound, while the dog barks, and the cat meows.


Comments