class property initialisers inheritance swift

By | August 7, 2016

class property initialisers inheritance swift

As we know, In swift, we must initialise the property values within the class definition. It can be done using default initialisers – that means assigning values to variables directly when we know that the value is never going to be changed in any of its instances or by using init function we do so.

When we are dealing with inheritance and have to modify certain property value within subclass then we use init function which is overridden using override keyword.

For example

Here, in subclass bicycle we override the super class initialiser. Then we call super.init() function. This calls the default initialiser and assigns the value 0 to a. Then we change the value of a.

Creating the object of bicycle and accessing a’s value will result into a = 2 whereas with super class object that supObj accessing a will call default initialiser and result into a =0 for that instance.