简体   繁体   English

实例初始化块和子类

[英]Instance initialization block and subclasses

I'm getting confused about when the instance initialization block should run. 我对何时应该运行实例初始化块感到困惑。 According to Kathy Sierra's book: 根据Kathy Sierra的书:

Instance init blocks run every time a class instance is created 实例初始化块在每次创建类实例时运行

So, consider having two classes: a parent and a child, according to this question and java's documentation: 因此,根据此问题和Java文档,考虑具有两个类:父级和子级:

instantiating a subclass object creates only 1 object of the subclass type, but invokes the constructors of all of its superclasses. 实例化一个子类对象仅创建一个子类类型的对象,但调用其所有超类的构造函数。

According to the above: why does the instance initialization block located in superclasses gets called every time an object of the subclass is instantiated? 根据以上所述: 为什么每次实例化子类的对象时都调用位于超类中的实例初始化块? it isn't like that a new object of the superclass is instantiated. 并非实例化超类的新对象。

After compilation instance init blocks become part of constructors. 编译后,实例init块成为构造函数的一部分。 javac simply adds the init block to each constructor, that is this: javac只需将init块添加到每个构造函数中,就是这样:

public class Test1 {
    int x;
    int y;

    {
        x = 1;
    }

    Test1() {
        y = 1;
    }
}

Is equivalent to this: 等效于此:

public class Test1 {
    int x;
    int y;

    Test1() {
        x = 1;
        y = 1;
    }
}

So the init block runs when constructor runs. 因此,init块在构造函数运行时运行。

it isn't like that a new object of the superclass is instantiated. 并非实例化超类的新对象。

Actually, it is like that. 其实就是这样。

Every instance of a subclass implicitly contains an instance of its superclass. 子类的每个实例都隐式包含其超类的实例。

A superclass constructor is always invoked as the first step in any constructor (and that in turn runs any instance initializer blocks for the superclass) 在任何构造函数中,第一步始终会调用超类构造函数(并依次为该超类运行任何实例初始化程序块)

Though it was a old post I came across this concept thought worth sharing it 虽然这是一个古老的帖子,但我遇到了这个概念,值得分享

Since we are talking about instance block here is how instance code flow executes in parent child relation class // Child extends Parent If we create a object for Child 既然我们正在谈论实例块,那么这就是实例代码流如何在父子关系类中执行//子扩展父对象如果我们为子对象创建对象

1) Identification of instance members of the class from parent to child 1)从父级到子级确定类的实例成员

2) execution of instance variable assignments and instance blocks only on parent class 2)仅在父类上执行实例变量分配和实例块

3)execution of parent constructor 3)执行父构造函数

4)execution of instance variable assignments and instance blocks only on Child class 4)仅在Child类上执行实例变量分配和实例块

5)Execution of child constructor 5)执行子构造函数

因为在子代的构造函数中始终存在对父代的构造函数的隐式super()调用(如果未显式完成)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM