I'm on solving some Java puzzles and stumbled on this one:
public class Outer {
class Inner1 extends Outer {}
class Inner2 extends Inner1 {}
}
While compiling this code with javac 1.6.0_45
I'm getting, as expected, this error:
Outer.java:8: cannot reference this before supertype constructor has been called
class Inner2 extends Inner1 {}
^
This is because of compiler generates default constructor for Inner2
class with similar code, which explains error above:
Inner2 () {
this.super();
}
And it's obvious now, because you really can't do this in Java 1.6.0_45, JLS 8.8.7.1 (as I can guess):
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.
See (accepted answer in Odd situation for "cannot reference this before supertype constructor has been called")
But if I try to compile it with javac 1.7.0_79
- it is OK!
And here goes the question - What has been changed in Java 1.7, that this code is now correct?
Thanks in advance!
Looks like there was discussion of the same problem as the bug JDK-6708938: Synthetic super-constructor call should never use 'this' as a qualifier on the Java bug tracker.
Also I think it would be great for you to take a look at other Related issues of previous one, for example JDK-4903103: Can't compile subclasses of inner classes .
Notice the Fixed Versions of both bugs.
And as the result see Maintenance Review of JSR 901 (Java Language Specification) for Java SE 7.
From The Java Language Specification Third Edition
Otherwise,
S
is an inner member class (§8.5). It is a compile-time error ifS
is not a member of a lexically enclosing class, or of a superclass or superinterface thereof. LetO
be the innermost lexically enclosing class of whichS
is a member, and let n be an integer such thatO
is the n th lexically enclosing class ofC
. The immediately enclosing instance ofi
with respect toS
is the n th lexically enclosing instance of this.
And from Maintenance Review of JSR 901 (Java Language Specification) for Java SE 7 (full version, page 242, blue text) or the same in The Java Language Specification, Java SE 7 Edition (just before section 8.8.8)
Otherwise, S is an inner member class (§8.5).
Let O be the innermost lexically enclosing class of S, and let n be an integer such that O is the n'th lexically enclosing class of C.
The immediately enclosing instance of i with respect to S is the n'th lexically enclosing instance of this.
So you can see that the part with compile-time error has gone.