Constructor voodoo
Can someone remind me why this doesn't work?
public class Foo {
String foo1 = null;
String foo2 = null;
public Foo(String value1, String value2)
{
foo1 = value1;
foo2 = value2;
init();
}
// I expect subclasses to override this and
// do something
protected void init()
{
// do nothing
}
}
-----
import java.util.*;
public class Bar extends Foo {
private List myList = null;
public Bar(String value1, String value2)
{
super(value1, value2);
}
protected void init()
{
System.err.println("Called init");
myList = new ArrayList();
System.err.println("My list = " + myList + " at end of init()");
}
public List getMyList()
{
return myList;
}
public static void main(String[] args)
{
Bar b = new Bar("test", "test2");
List l = b.getMyList();
System.err.println("My list = " + l + " in main");
}
}
The output of running Bar is:
So what appears to happen is that init() is called, but then myList gets
set to null, just as it was declared at the start of the class definition. I know constructors do not work like "normal" methods, but other than shrugging my shoulders in confusion, can someone explain why it behaves like this? I feel like I puzzled this out once before, but the answer is eluding me at 1:00am EST.
...and yes, I know I could have done this another way. I already rewrote the (more complex) classes that led me to discover this "feature". At this point, it's pure curiousity.
public class Foo {
String foo1 = null;
String foo2 = null;
public Foo(String value1, String value2)
{
foo1 = value1;
foo2 = value2;
init();
}
// I expect subclasses to override this and
// do something
protected void init()
{
// do nothing
}
}
-----
import java.util.*;
public class Bar extends Foo {
private List myList = null;
public Bar(String value1, String value2)
{
super(value1, value2);
}
protected void init()
{
System.err.println("Called init");
myList = new ArrayList();
System.err.println("My list = " + myList + " at end of init()");
}
public List getMyList()
{
return myList;
}
public static void main(String[] args)
{
Bar b = new Bar("test", "test2");
List l = b.getMyList();
System.err.println("My list = " + l + " in main");
}
}
The output of running Bar is:
Called init My list = [] at end of init() My list = null in main
So what appears to happen is that init() is called, but then myList gets
set to null, just as it was declared at the start of the class definition. I know constructors do not work like "normal" methods, but other than shrugging my shoulders in confusion, can someone explain why it behaves like this? I feel like I puzzled this out once before, but the answer is eluding me at 1:00am EST.
...and yes, I know I could have done this another way. I already rewrote the (more complex) classes that led me to discover this "feature". At this point, it's pure curiousity.
