Bug: Field initialization skipped when using 'this(…)' statement

6 views
Skip to first unread message

Udo

unread,
May 28, 2013, 8:58:24 AM5/28/13
to java2...@googlegroups.com
It looks like the field initialization of an object is not performed when a constructor uses the 'this(…)' statement to delegate the execution to a different constructor of the class.

Here an example:

--- BaseClass.java ---

public class BaseClass {
public boolean f;

BaseClass(boolean f) {
this.f = f;
}
}

----------------------

--- SubClass.java ---

import java.util.ArrayList;
import java.util.List;

public class SubClass extends BaseClass {
public List<String> strings = new ArrayList<String>();
SubClass() {
this(true); // BUG: Calling 'this(...)' skips the field initialization
}

SubClass(boolean f) {
super(f);
}

public static void main(String[] args) {
SubClass obj = new SubClass();
obj.strings.add("foo");
System.out.println(obj.strings.size());
System.out.println(obj.strings.get(0));
}
}

----------------------


Running SubClass.main in Java will prompt (as expected):
1
foo


Running the same code using Java2Script however ends with an error:
TypeError: 'null' is not an object (evaluating 'obj.strings.add')

This error occurs because the member field 'strings' is not initialized.

Directly calling 'super(true)' in the constructor 'SubClass()‘ correctly initializes the strings field.


Udo
Reply all
Reply to author
Forward
0 new messages