Relates :
|
|
Relates :
|
|
Relates :
|
FULL PRODUCT VERSION : >javac -version javac 1.6.0 >java -version java version "1.6.0" Java(TM) SE Runtime Environment (build 1.6.0-b105) Java HotSpot(TM) Client VM (build 1.6.0-b105, mixed mode, sharing) ADDITIONAL OS VERSION INFORMATION : Windows XP A DESCRIPTION OF THE PROBLEM : JLS Chapter 16, first paragraph: "Each local variable (��14.4) and every blank final (��4.12.4) field (��8.3.1.2) must have a definitely assigned value when any access of its value occurs. " The code below throws a null pointer exception because a final field is read before being assigned. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : Compile and run code below EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - For the program to exit normally. ACTUAL - Null pointer exception ERROR MESSAGES/STACK TRACES THAT OCCUR : >java ndafinal Exception in thread "main" java.lang.NullPointerException at B.f(ndafinal.java:15) at A.<init>(ndafinal.java:9) at B.<init>(ndafinal.java:13) at ndafinal.main(ndafinal.java:4) REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- class ndafinal { public static void main(String[] args) { // causes null pointer error new B(); } } class A { A() { f(); } int f() { return 0; } } class B extends A { private final Object o = new Object(); int f() { return o.hashCode(); } } ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : In more complex applications, it becomes necessary to check if a final field is not null before relying on its value, partly defeating the point of the "final" keyword. IMO either final fields should be assigned before the super constructor is called, or the JLS should be clarified to indicate that access of an unassigned final field is possible and has a definate value (i.e. null).
|