If I have abstract class A with an init method:
abstract class A(){
init {
println(\"Hello\")
}
}
And then class B that extend
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:
An object is allocated.
The constructor of the class is called. (a)
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)
If the class has property initializers or init
blocks, they are executed in the same order as they appear in the class body;
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.