实例初始化块和子类 [英] Instance initialization block and subclasses
问题描述
我对何时应该运行实例初始化块感到困惑. 根据凯西·塞拉(Kathy Sierra)的书:
I'm getting confused about when the instance initialization block should run. According to Kathy Sierra's book:
实例初始化块在每次创建类实例时运行
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:
实例化一个子类对象仅创建该子类的1个对象 类型,但调用其所有超类的构造函数.
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.
推荐答案
编译实例后,init块成为构造函数的一部分. javac
只需将init块添加到每个构造函数中,即:
After compilation instance init blocks become part of constructors. javac
simply adds the init block to each constructor, that is this:
public class Test1 {
int x;
int y;
{
x = 1;
}
Test1() {
y = 1;
}
}
等效于此:
public class Test1 {
int x;
int y;
Test1() {
x = 1;
y = 1;
}
}
因此init块在构造函数运行时运行.
So the init block runs when constructor runs.
这篇关于实例初始化块和子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!