JDK-6275018 : Bad initialization of members when accessed by a super class' constructor
  • Type: Bug
  • Component: tools
  • Sub-Component: javac
  • Affected Version: 1.4.2,6
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: linux,windows_xp
  • CPU: x86
  • Submitted: 2005-05-24
  • Updated: 2010-04-02
  • Resolved: 2007-05-14
Related Reports
Duplicate :  
Relates :  
Description
FULL PRODUCT VERSION :
java version "1.4.2_06"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_06-b03)
Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode)

ADDITIONAL OS VERSION INFORMATION :
Microsoft Windows XP [Version 5.1.2600]

A DESCRIPTION OF THE PROBLEM :
When an abstract class' constructor invokes an abstract method and the implementation of that method accesses a member of the subclass, the member isn't properly initialized and has a null value.

Either the compiler should warn (or even throw an error) in these use-cases or the members should be initialized before the execution of the super() call.

Please check the following steps to reproduce.

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
public abstract class Hello
{

  public Hello()
  {
    abstractMethod();
  }

  public abstract void abstractMethod();

}
public class World extends Hello
{
  private String xpto = "hello world";
  public World()
  {
    super();
  }

  public void abstractMethod()
  {
    System.out.println(xpto);
  }

  public static void main(String[] args)
  {
    new World();
    System.out.println("done...\n");
  }
}


EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Either the compiler should warn about the possibility of the member not being initialized or the member should be initializer prior to the execution of super().

Another alternative is to initialize the member when it's first accessed.
ACTUAL -
xpto == null

REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
Same as steps to reproduce
---------- END SOURCE ----------
###@###.### 2005-05-24 05:54:44 GMT

Comments
EVALUATION This is not a spec bug. Only after Hello's constructor finishes will World's instance variables be initialized, as per JLS12.5. The constructor body and instance variable initializers in a subclass can refer to instance variables in a superclass. Thus, it is essential to run the subclass's constructor and instance variable initializers AFTER the superclass's constructor and instance variable initializers. Your expected behaviour assumes the subclass's instance variable initializers run BEFORE the superclass's constructor and instance variable initializers. It would be ideal if the compiler gave a -Xlint warning when Hello's constructor calls a method which is necessarily overridden in World.
03-11-2006