In object-oriented programming, inheritance refers to one class (known as a sub or child class) being derived from another class (known as a super or parent class). The subclass will inherit methods, properties, and other characteristics from the superclass. With inheritance, we can also create a class hierarchy where we can have multiple layers of inheritance.
Let's look at how we could create a class hierarchy with classes in Swift. We will start off by creating a base class named Animal
:
class Animal { var numberOfLegs = 0 func sleeps() { print("zzzzz") } func walking() { print("Walking on \(numberOfLegs) legs") } func speaking() { print("No sound") } }
In the Animal
class, we defined one property (numberOfLegs
) and three methods (sleeps()
, walking()
, and speaking()
). Now, any class that is a subclass of the Animal
class will also have these properties and methods. Let's see how this works by creating two classes...