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:
- Static initialization for
B
and its dependents is triggered (if this hasn't happened already).
- Argument expressions for
B
's constructor parameters are evaluated evaluated. (There aren't any, in this case.)
- A heap node is created, initialized with
B
's type, and all fields (in B
and its superclasses) are default initialized.
- The
super
parameters for B
are evaluated.
- The
super
parameters for A
are evaluated.
- The
Object()
constructor body is executed.
- The fields
A.i
and A.y
would be initialized (if they had initializers).
- The
A(int,int)
constructor body is executed.
B
's field initializers would be executed.
- The
B()
constructor body is executed.
- 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!