Swift - Inheriting from a Base Class

Introduction

To inherit from a base class, you create another class and specify the base class name after the colon :

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)
    }
}

class Rectangle : Shape  {

}

Here, Rectangle is a subclass of Shape.

Rectangle inherits all the properties and methods declared in the Shape class.

However, you are still not able to create an instance of the Rectangle class yet, because you need to create an initializer for the Rectangle class.

Overriding Initializers

Shape class has a private initializer that is only visible to code that resides in the same physical file as the Shape class.

In order to be able to create an instance of the Rectangle class, you need to provide an initializer, as shown here:


class Rectangle: Shape {
     //override the init() initializer
     override init() {
         super.init()
     }
}

You need to prefix the init() initializer with the override keyword.

This is because the init() initializer is already in the base class Shape.

Because you are overriding the initializer, you need to call the immediate superclass's init() method before exiting this initializer:


override init() {
     super.init()
}

You will now be able to create an instance of the Rectangle class:

var rectangle = Rectangle ()

You can access the length and width properties of the Shape base class:

rectangle.length = 5                                                           
rectangle.width = 6

The following example shows how you can also access the perimeter() method defined in the Shape class:

print(rectangle.perimeter()) //22.0                                        

Demo

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

     //improvision to make the class abstract
    private init() {
         length = 0/*from  ww w.  j a v  a2 s  .  c  om*/
         width = 0
    }

    func perimeter() -> Double {
        return 2 * (length + width)
    }
}
class Rectangle: Shape {
     //override the init() initializer
     override init() {
         super.init()
     }
}
var rectangle = Rectangle ()

rectangle.length = 5                                                           
rectangle.width = 6
print(rectangle.perimeter()) //22.0

Related Topic