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:
- Reuse the field of the type
A, inherited fromX, and inside the classY, castAtoB. This makes my code full of nasty type casts. - Add another field of the type
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. - Add all methods that
Bprovides also toA, throwNotImplementedException. 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: