Accessing final instance variables inside constructur before initialized
Alex Buckley
alex.buckley at oracle.com
Fri Feb 13 17:51:21 UTC 2015
javac is correctly implementing the JLS 16.9 specification:
"If C [here, SubClass] has no instance initializers or instance variable
initializers, then V [here, test] is not definitely assigned (and
moreover is definitely unassigned) after an explicit or implicit
superclass constructor invocation."
Alex
On 2/13/2015 3:31 AM, Tom Schindl wrote:
> Hi,
>
> I came across some code which compiles and works fine (at runtime) with
> the Eclipse Java Compiler but fails with javac (8u40).
>
> I've stripped it down to this (the original code used lambda expression
> accessing the instance field).
>
>>
>> public abstract class CompilerTest {
>>
>> public CompilerTest() {
>> System.err.println("Constructor Base: " + getTest());
>> }
>>
>> protected abstract String getTest();
>>
>> static class SubClass extends CompilerTest {
>> private final String test;
>>
>> public SubClass(String test) {
>> System.err.println(this.test); // javac fails
>> this.test = test;
>> System.err.println(this.test);
>> }
>>
>> @Override
>> protected String getTest() {
>> return this.test;
>> }
>>
>> }
>>
>> public static void main(String[] args) {
>> new SubClass("Hello World!");
>> }
>> }
>
> So javac fails with
>
>> CompilerTest.java:14: error: variable test might not have been initialized
>> System.err.println(this.test);
>
> One might argue that most likely the above code is a really not what the
> user idented to do but I'm still not sure javac is correct in refusing
> to compile this piece of code.
>
> Tom
>
More information about the compiler-dev
mailing list