Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init method inheritance

Tags:

kotlin

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?

like image 750
Graham Avatar asked May 03 '17 17:05

Graham


People also ask

What is __ Init__ method?

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.

Do child classes need init?

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.

What is __ init __ In OOP?

"__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.

What does init () do?

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.


Video Answer


1 Answers

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.

like image 193
hotkey Avatar answered Dec 03 '22 08:12

hotkey