schrobe
schrobe

Reputation: 837

How to define constants/final variables in abstract superclasses but assign them in the subclass?

I have a abstract class where I want to declare final variables.

However, I want to assign the values to these variables only in the constructors of my sub-classes.

Apparently, this is not possible because all "final fields have to be initialized". I do not see why, since it is not possible anyway to instantiate an abstract class.

What I would like to have is something like this:

abstract class BaseClass {
    protected final int a;
}

class SubClass extends BaseClass {
    public SubClass() {
        a = 6;
    }
}

I imagine something similar to methods when you implement an interface. Then you are also forced to to implement the methods in the (sub-)class.

Upvotes: 12

Views: 7042

Answers (1)

Vikdor
Vikdor

Reputation: 24124

You should define a constructor in your abstract class that takes a value for a and call this constructor from your sub classes. This way, you would ensure that your final attribute is always initialized.

abstract class BaseClass {
    protected final int a;

    protected BaseClass(int a)
    {
        this.a = a;
    }
}

class SubClass extends BaseClass {
    public SubClass() {
        super(6);
    }
}

Upvotes: 17

Related Questions