Badda
Badda

Reputation: 1369

Use child's attribute in parent's constructor

class abstract Parent ()
{
     private int a;
     private final int b = a + 1; // a is null at that point
}

class Child extends Parent
{
    public Child()
    {
       a = 2;
    }
}

That wouldn't really be a problem in C++ (because pointers), but I'm not sure how to handle this issue in Java. Obviously a is equal to 0 when Parent tries to initiate b.

I initially tried calling super() after setting a, but apparently super() has to be called first in child's constructor. I don't want to set b in Childs and I'd prefer b to be final too. Any ideas?

Upvotes: 0

Views: 557

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 109256

What you want cannot be done like this, what you need to do is pass the value of a to a constructor of Parent:

abstract class Parent {
    private int a;
    private final int b;

    protected Parent(int a) {
        this.a = a;
        b = a + 1;
    }
}

And define Child as:

class Child extends Parent {
    public Child() {
        super(2);
    }
}

Upvotes: 2

Related Questions