Subclassing and Extensions
Explore the concepts of subclassing, inheritance, and extensions in Swift.
We'll cover the following...
In earlier lessons, we covered the basic concepts of object-oriented programming and worked through an example of creating and working with a new class using Swift. In that example, our new class was not derived from any base class and as such, did not inherit any traits from a parent or superclass. In this lesson, we will introduce the concepts of subclassing, inheritance and extensions in Swift.
Inheritance, classes, and subclasses
The concept of inheritance brings something of a real-world view to programming. It allows a class to be defined that has a certain set of characteristics (such as methods and properties) and then allows other classes to be created, which are derived from that class. The derived class inherits all of the features of the parent class and then typically adds some features of its own.
By deriving classes, we create what is often referred to as a class hierarchy. The class at the top of the hierarchy is known as the base class or root class, and the derived classes are known as subclasses or child classes. Any number of subclasses may be derived from a class. The class from which a subclass is derived is called the parent class or superclass.
Classes need not only be derived from a root class. For example, a subclass can also inherit from another subclass with the potential to create large and complex class hierarchies.
In Swift, a subclass can only be derived from a single direct parent class. This is a concept referred to as single inheritance.
A Swift inheritance example
As with most programming concepts, the subject of inheritance in Swift is perhaps best illustrated with an example. Previously, we created a class named BankAccount
that was designed to hold a bank account number and corresponding current balance. The BankAccount
class contained both properties and instance methods. A simplified declaration for this class is reproduced below:
class BankAccount {
var accountBalance: Float
var accountNumber:
...