Why Cannot refer to instance fields while explicitly invoking a constructor java

后端 未结 1 1256
终归单人心
终归单人心 2021-01-15 12:36

Hi I have below simple classes.

class A {
int i;
int y;

A(int i, int y)
{

}

and then when I try to do below

class B exte         


        
相关标签:
1条回答
  • 2021-01-15 13:25

    Since A's constructor gets initialized first it has 0 value for both i and y and why cannot pass those values to super constructor.

    The problem is that expressions for the arguments in super(i, y) (in B) are evaluated before calling the A constructor.

    The execution sequence for new B() is as follows:

    1. Static initialization for B and its dependents is triggered (if this hasn't happened already).
    2. Argument expressions for B's constructor parameters are evaluated evaluated. (There aren't any, in this case.)
    3. A heap node is created, initialized with B's type, and all fields (in B and its superclasses) are default initialized.
    4. The super parameters for B are evaluated.
    5. The super parameters for A are evaluated.
    6. The Object() constructor body is executed.
    7. The fields A.i and A.y would be initialized (if they had initializers).
    8. The A(int,int) constructor body is executed.
    9. B's field initializers would be executed.
    10. The B() constructor body is executed.
    11. The reference to completed B instance is returned.

    As you can see, step 4 refers to y which hasn't been initialized yet1. It won't be initialized until step 7.

    Note: the above is simplified. Refer to JLS 15.9.4 for the full specification.


    1 - The rules don't take account of the fact that there is no initializer in your example. But that's a good thing. 1) Taking account of that would make them more complicated and ... surprising. 2) What is the utility of allowing access to a variable if you know it has the default value? You could just use that value directly!

    0 讨论(0)
提交回复
热议问题