Field assignment in early construction context - details
Stephan Herrmann
stephan.herrmann at berlin.de
Sun Jul 14 17:43:33 UTC 2024
Dear experts,
I'm observing some more differences between the JEP 482 spec [1] and javac [2],
which may or may not be omissions in JLS:
(1) §6.5.6.1 regulates access to fields of C within an early construction
context of C, but it does not mention any inheritance situations like this:
class Super {
int i;
}
public class Test extends Super {
Test() {
i = 13;
super();
}
}
javac reports:
error: cannot reference i before supertype constructor has been called
i = 13;
^
First of all, do we have a relevant early construction context at all?
- i is declared in Super
- we are not in an early construction context of Super
- should we consider i as an instance variable of Test?
- should early construction context affect all super classes, too?
Then if we had an early construction context affecting 'i', wouldn't the
"assignment exception" apply, or should super fields be exempted from the exception?
Most certainly, it is not intended to admit *reading* 'i' in an early
construction context of 'Test', but I don't see anything in this direction in
the spec.
(2) §15.8.3 admits 'this' in early construction context when "it appears as the
qualifier of a field access expression appearing as the left-hand operand of a
simple assignment expression". §15.8.4 has no such exception for qualified this,
even if the qualifier is redundant:
public class Test {
int j;
Test() {
Test.this.j = 15;
super();
}
}
'Test.this' clearly appears in an early construction context of 'Test'.
Still javac accepts, and in this case I don't see any reason to reject.
Is this an omission in §15.8.4?
thanks,
Stephan
[1] Latest as of
https://cr.openjdk.org/~iris/se/23/spec/draft/java-se-23-draft-spec-31/
[2] from build 23-ea+31-2337
More information about the amber-spec-experts
mailing list