related to compile error in preview feature 'record'
Alex Buckley
alex.buckley at oracle.com
Wed Sep 30 16:50:22 UTC 2020
In the compact constructor below, `low` refers to an implicit parameter
of the constructor, whereas `this.low` refers to a field corresponding
to the record component `low`.
IIRC, the field is not definitely assigned before the end of the
constructor body, so referring to `this.low` anywhere in the constructor
body is an error by the traditional rule at the beginning of JLS ch.16.
There is no interprocedural analysis in ch.16, so m1's independent
reference to a field via `this.low` is allowed on the basis that the
field was definitely assigned by the end of every constructor body.'
In an ordinary class, a constructor body that calls m1() but forgets to
explicitly initialize the field would cause a compile-time error. There
is no corresponding compile-time error here because the compact
constructor body implicitly initializes the field.
Alex
On 9/30/2020 8:45 AM, Pravin Jain wrote:
> Dear sir,
> In the following code, I have commented the error.
> This error seems to be unnecessary, could have been a warning instead.
> In the constructor of record access to instance variable before
> explicit initialization, giving error, whereas same access is
> available by invoking a method.
>
> public record TestRecord(int low, int high) {
> public TestRecord {
> System.out.println(low);
> // System.out.println(this.low); // error, variable not initialized
> m1(); // but this works, why?
> }
> public void m1() {
> System.out.println(this.low);
> }
> public static void main(String[] args) {
> TestRecord r1 = new TestRecord(7,12);
> }
> }
>
>
More information about the compiler-dev
mailing list