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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With