Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 787
schrobe Avatar asked Oct 20 '12 12:10

schrobe


1 Answers

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);
    }
}
like image 101
Vikdor Avatar answered Oct 21 '22 04:10

Vikdor