Thursday, October 8, 2009

Be Careful Calling Non-Final methods in Constructors

My co-worker taught me to be careful about calling non-final methods from class constructors today.


public class Test {

public static void main(String[] args) {
new Child();
}


public static class Parent {

public Parent() {
System.out.println("Parent Initializing.");
doOne();
doTwo();
}

private void myDoOne() {
System.out.println("Parent doOne");
}

public void doOne() {
myDoOne();
}

public void doTwo() {
System.out.println("Parent doTwo");
}
}

public static class Child extends Parent {

public Child() {
super();
System.out.println("Child initializing.");
doOne();
doTwo();
}

public void doOne() {
System.out.println("Child doOne");
}
}
}

This will produce this output:

Parent Initializing.
Child doOne
Parent doTwo
Child Initializing.
Child doOne
Parent doTwo


This is dangerous, because now the behavior of the parent constructor has changed, which can leave the parent object in an unknown state. So, lesson learned, if you're going to call methods in your constructor, make sure descendant classes can't override them.