Swift - Inheritance and abstract class

Introduction

Class inheritance means that a class can inherit the properties and methods from another class.

Class inheritance allows the same implementation to be adapted for another use.

Swift fully supports the capability of class inheritance.

Defining a Base Class

A base class is a class that does not inherit from another class.

For example, the following Shape class does not inherit from any class, and hence it is known as a base class:


class Shape {
    //stored properties
    var length:Double = 0
    var width:Double = 0


    func perimeter() -> Double {
        return 2 * (length + width)
    }
}

The Shape class contains two stored properties, length and width , as well as a perimeter() method.

This class does not assume that an object has any particular shape;

It assumes that an object has a measurable length and width, and that its perimeter is twice the sum of its length and width.

Creating an Abstract Class

OOP includes the concept of abstract classes.

Abstract classes are classes from which you cannot directly instantiate.

You cannot create an instance of the abstract class directly.

You can only create an instance of its subclass.

In Swift, abstract classes are not supported, use protocols to implement the concept of abstract classes if you need to.

However, you can improvise an abstract method by using the private identifier together with an initializer, as shown here:

class Shape {
    //stored properties
    var length:Double = 0
    var width:Double = 0

     //improvision to make the class abstract
    private init() {
         length = 0
         width = 0
    }

    func perimeter() -> Double {
        return 2 * (length + width)
    }
}

Here, you added a private initializer, init(), which limits its accessibility to within its physical file.

Any code that is outside the physical file in which the Shape class is defined will not be able to call the initializer method.

Related Topic