Accessing final instance variables inside constructur before initialized

Tom Schindl tom.schindl at bestsolution.at
Fri Feb 13 11:31:17 UTC 2015


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

-- 
Thomas Schindl, CTO
BestSolution.at EDV Systemhaus GmbH
Eduard-Bodem-Gasse 5-7, A-6020 Innsbruck
http://www.bestsolution.at/
Reg. Nr. FN 222302s am Firmenbuchgericht Innsbruck


More information about the compiler-dev mailing list