Instance initialization block and subclasses

拜拜、爱过 提交于 2019-12-24 00:54:52

问题


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:

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.


回答1:


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;
    }
}

Is equivalent to this:

public class Test1 {
    int x;
    int y;

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

So the init block runs when constructor runs.




回答2:


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)




回答3:


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

2) execution of instance variable assignments and instance blocks only on parent class

3)execution of parent constructor

4)execution of instance variable assignments and instance blocks only on Child class

5)Execution of child constructor




回答4:


Because there is always an implicit super() call(if not done explicitly) to the parent's constructor in the constructor of the child.



来源:https://stackoverflow.com/questions/16128076/instance-initialization-block-and-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!