Class-initialization hierarchy

In the previous section, we explored the functionalities of inheritance by extending the Person class with the student and professor classes. In this section, we will have a closer look at the constructor and class-initialization. Let's take a very simple example:

  1. Create a super or parent class, A, with the init function.
  2. Create a similar class, B, with the init function and extend it with the A class. Do the same with the C class.
  3. Add a print message in each init function. The init function will be called just before the initialization of the constructor:
open class A {
init {
println("Class A is initialized")
}
}

open class B : A() {
init {
println("Class B is initialized")
}
}

class C : B() {
init {
println("Class C is initialized")
}
}

fun main(args: Array<String>) {
// val a = A()
val c = C()
}

When a base or non-derived class is called, Kotlin creates a constructor of the class. When a derived class is initialized, however, things are not so straightforward:

As we know, the derived class inherits all properties and behaviors from the base class and these properties must be initialized before we use them. Usually, all properties are initialized in either the primary or the secondary constructor. When the derived class is instantiated, the constructor of the derived class calls its superclass constructor as part of its initialization. This superclass checks whether it is derived from another class. If it has no parent class, it initializes all properties and sends the control back to the derived class to initialize its properties. In our case, class C is derived from class B, and class B is derived from class A. When the object of class C is initialized, it jumps to the class B constructor and class B jumps to class A. This means that the first print statement comes from class A, the second from class B, and the last from class C.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.175.253