初始化方法继承 [英] Init method inheritance

查看:113
本文介绍了初始化方法继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个带有初始化方法的抽象类A:

If I have abstract class A with an init method:

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

然后是扩展A的B类

class B(): A()

如果我像这样实例化B

If I instantiate B like this

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

A中的init方法是否仍然运行并打印Hello?

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

如果没有,我该怎么做才能让A的init方法运行?

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

推荐答案

是的,初始化派生类实例时,将运行基类的init块.

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

在Kotlin中,类似于Java,按以下方式构造类的实例:

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

  1. 已分配一个对象.

  1. An object is allocated.

该类的构造函数被调用. (a)

The constructor of the class is called. (a)

  1. 如果类具有超类,则在执行类构造逻辑之前会调用超类构造函数
    (即,对超类递归执行(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)

如果该类具有属性初始化器或init块,则它们将按照它们在类主体中出现的顺序执行;

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.

在此描述中,您可以看到,在构造B时,在执行B初始化逻辑之前,尤其是在A的所有init块之前,将调用A的构造函数.被执行.

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.

(此逻辑的可运行演示)

关于术语的小注释:init块实际上不是单独的方法.相反,所有init块与成员属性初始化程序一起都被编译到构造函数的代码中,因此应将它们视为构造函数的一部分.

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.

这篇关于初始化方法继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆