Inheritance in Swift
Introduction
In Swift, inheritance is a fundamental concept of Object-Oriented
Programming that allows one class (called the subclass or child
class) to acquire properties and methods from another class (called
the superclass or parent class). This mechanism promotes code
reusability and hierarchical classifications.
A subclass can extend or override functionalities of the superclass,
enabling specialized behaviors without rewriting the existing code.
Inheritance also supports method overriding, where the subclass
provides a specific implementation of a method defined in its
superclass.
Key Points to Remember
- The class that inherits properties and methods is called the subclass, while the class being inherited from is the superclass.
-
A subclass can override methods and properties of its superclass
using the
override
keyword. - Swift does not support multiple inheritance, meaning a class can inherit from only one superclass.
- Subclasses can add new properties and methods in addition to what they inherit.
- Initializers can be overridden in the subclass to customize object creation.
Syntax
class Superclass {
// Properties and methods
}
class Subclass: Superclass {
// Additional properties and methods
// Overridden properties and methods
}
Example 1: Inheriting Properties and Methods
Let's demonstrate how a subclass inherits properties and methods from a superclass in Swift.
import Foundation
class Vehicle {
var brand: String
init(brand: String) {
self.brand = brand
}
func honk() {
print("Beep! Beep!")
}
}
class Car: Vehicle {
var model: String
init(brand: String, model: String) {
self.model = model
super.init(brand: brand)
}
func displayDetails() {
print("Brand: \(brand), Model: \(model)")
}
}
let car1 = Car(brand: "Toyota", model: "Corolla")
car1.honk()
car1.displayDetails()
Output
Brand: Toyota, Model: Corolla
Example 2: Overriding Methods in Subclass
In this example, we will see how a subclass can override a method of its superclass to provide specific behavior.
import Foundation
class Animal {
func sound() {
print("Animal makes a sound")
}
}
class Dog: Animal {
override func sound() {
print("Dog barks")
}
}
let myDog = Dog()
myDog.sound()