Daniel Calderon Mori
Daniel Calderon Mori

Reputation: 5796

How to use an attribute of a child class in the superclass constructor?

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?

Upvotes: 0

Views: 1012

Answers (2)

Mohsin
Mohsin

Reputation: 852

Your super class has an abstract method

`abstract public void createBody();` 

declare the super class as abstract ,since super class must be an abstract class to define abstract methods.

Secondly, you should not make a call to the createBody method from super class constructor since it may be using variables which could not have been even initialized.

//do some stuff
//assign attribute x  <--- never do such stuffs 

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

May I warn you that you are in perilous waters here. As you work on it, you'll probably realize you want to call createBody in 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 as

private final String x = "string";

has not yet run and x is null. This is an anti-idiom for Java and you should avoid it at all cost.

Upvotes: 3

Related Questions