Types of Inheritance
Swift supports different types of inheritance, depending on the relationship between the classes involved. Some of the common types of inheritance are:
1. Single inheritance
A subclass inherits from only one superclass. This is the most common type of inheritance in Swift. For example:
class Vehicle
{
// properties and methods of Vehicle
}
class Car: Vehicle
{
// properties and methods of Car
}
Here, the Car class inherits from the Vehicle class, which means that a Car instance can access the properties and methods of the Vehicle class, as well as its properties and methods.
2. Multilevel inheritance
A subclass inherits from another subclass, which in turn inherits from a superclass. This creates a chain of inheritance from the top-level superclass to the bottom-level subclass. For example:
class Vehicle
{
// properties and methods of Vehicle
}
class Car: Vehicle
{
// properties and methods of Car
}
class ElectricCar: Car
{
// properties and methods of ElectricCar
}
Here, the ElectricCar class inherits from the Car class, which in turn inherits from the Vehicle class. This means that an ElectricCar instance can access the properties and methods of all three classes in the hierarchy.
3. Multiple inheritance
A subclass inherits from more than one superclass. This allows a subclass to combine the features and behaviors of multiple superclasses. However, Swift does not support multiple inheritance for classes directly. Instead, Swift uses protocols to achieve a similar effect. A protocol defines a set of requirements that a conforming type must implement, such as properties, methods or subscripts. A class can conform to multiple protocols by listing them after the colon: in its declaration. For example:
protocol Flyable
{
// requirements for flying
}
protocol Swimable
{
// requirements for swimming
}
class Duck: Animal, Flyable, Swimable
{
// properties and methods of Duck
}
Here, the Duck class inherits from the Animal class and also conforms to the Flyable and Swimable protocols. This means that a Duck instance can access the properties and methods of the Animal class, as well as the requirements of the two protocols.
Swift – Inheritance
Inheritance is one of the fundamental concepts of object-oriented programming (OOP) languages. It allows us to create a new class from an existing class and reuse the existing code and functionality. In this article, we will learn about inheritance in Swift and how to use it to create subclasses, override methods and properties, and implement polymorphism.