I have a class A which extends a B class and overrides a method createBody() which is called in the parent constructor:
public class A extends B {
SomeClass x = null
public A(int parameter) {
super(parameter);
//do something with atributte x
}
createBody() {
//do some stuff
//assign attribute x
}
}
public class B {
public B(int parameter) {
//do some stuff
createBody();
}
abstract public void createBody();
}
As you can see, the method createBody() modifies the x attribute. My problem is, the x attribute remains null once the superclass constructor is finished (when I create an instance of the child class). What am I doing wrong?
May I warn you that you are in perilous waters here. As you work on it, you’ll probably realize you want to call
createBodyin the superclass constructor, but implement it in the subclass. This way you are transferring control to a subclass method before that subclass’s initialization has even begun. For example, at that point even a line such ashas not yet run and x is null. This is an anti-idiom for Java and you should avoid it at all cost.