Dienstag, 19. Oktober 2010

Beware Abstract Methods During Construction of Java Objects

It should be common knowledge, but it happens anyway: During constructing a Java object an abstract method is called. The called method relies on the values initialized in the derived object. The result: unexpected behaviour and often hard to find errors. So always remember: Never call abstract methods during construction of a Java object! Neitherin the constructor nor while initializen the instance variables!

The behaviour can be seen executing the following little test class:

abstract class Parent {

    int value;

    public Parent() {
        value = dangerousInitializer();
    }

    protected abstract int dangerousInitializer();

}

class Child extends Parent {

    int desiredValue = 42;

    @Override
    protected int dangerousInitializer() {
        return desiredValue;
    }

}

public class Test {
    public static void main(String[] args) {
        Child child = new Child();
        System.out.println("child.desiredValue=" + child.desiredValue);
        System.out.println("child.value=" + child.value);
    }
}

The result:
child.desiredValue=42
child.value=0

Keine Kommentare:

Kommentar veröffentlichen