Init method inheritance

前端 未结 1 674
一生所求
一生所求 2021-01-18 22:57

If I have abstract class A with an init method:

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

And then class B that extend

相关标签:
1条回答
  • 2021-01-18 23:32

    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.

    0 讨论(0)
提交回复
热议问题