Init method inheritance

2019-02-25 14:47发布

问题:

If I have abstract class A with an init method:

abstract class A(){
  init {
    println("Hello")
  }     
}

And then class B that extends A

class B(): A()

If I instantiate B like this

fun main(args: Array<String>){
  B()
}

Does the init method in A still get run and Hello gets printed?

And if not, what do I need to do to have the init method of A get run?

回答1:

Yes, an init block of a base class gets run when the derived class instance is initialized.

In Kotlin, similarly to Java, an instance of a class is constructed in the following way:

  1. An object is allocated.

  2. The constructor of the class is called. (a)

    1. If the class has a superclass, the superclass constructor is called before the class construction logic is executed;
      (i.e., the point (a) is executed recursively for the superclass, then the execution continues from here)

    2. If the class has property initializers or init blocks, they are executed in the same order as they appear in the class body;

    3. If the constructor has a body (i.e. it is a secondary constructor) then the body is executed.

In this description, you can see that, when B is constructed, the constructor of A is called before B initialization logic is executed, and, in particular, all init blocks of A are executed.

(runnable demo of this logic)


A small remark on terminology: init block is not actually a separate method. Instead, all init blocks together with member property initializers are compiled into the code of the constructor, so they should rather be considered a part of the constructor.



标签: kotlin