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?
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
Absolutely not. The typical pattern is that the child might have extra fields that need to be set that the parent does not have, but if you omit the __init__ method completely then it inherits it from the parent which is the correct behavior in your case.
"__init__" is a reseved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.
init is just shorthand for initiate. Typically it is used to create a "new Object()". Like the init() function in jQuery returns a new jQuery object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With