I have some class X with the field A in it. It is a final field, initialized in constructor. Now I have a derived class Y where this field must always be an instance of B, a class that is derived from A. The problem, the class Y needs to call a number specific methods that are only available on the class B but not on its ancestor, A.
I see several solutions:
A, inherited from X, and inside the class Y, cast A to B. This makes my code full of nasty type casts.B. Now there are no typecasts but we have two fields of slightly different type that must always hold the same value - also does not feel good.B provides also to A, throw NotImplementedException. This adds some strange methods that knowingly make no sense in that class.Which is the most right way to deal with this field? Or maybe some other, better exists? I do not think this is very language specific but must be doable in Java I am using.
The X type should probably be a generic type:
public class X<T extends A> {
protected T a;
public X(T a) {
this.a = a;
}
}
public clas Y extends X<B> {
public Y(B b) {
super(b);
}
public void foo() {
// here, this.a is of type B, without any type cast.
}
}
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