I have a system of object instances that contain a reference to a definition object. I have a top-level class for each inheritance tree. The instance object has a generic reference to the corresponding definition class.
Using generics in the getter, a subclass of the top-level object can get the right type of definition without casting. However, an abstract subclass that is subclassed again cannot:
class Def { }
abstract class Animal<D extends Def> {
D def;
D getDef() { return def; }
}
class CatDef extends Def { }
class Cat extends Animal<CatDef> { }
abstract class BearDef extends Def { }
abstract class Bear<D extends BearDef> extends Animal<D> { }
class BlackBearDef extends BearDef { }
class BlackBear extends Bear<BlackBearDef> { }
class AnimalDefTest {
public static void main (String... args) {
Cat cat = new Cat();
CatDef catDef = cat.getDef(); // CatDef works fine
Bear bear = new BlackBear();
BearDef bearDef = bear.getDef(); // Error: Expected Def not BearDef? Why???
BearDef bearDef2 = ((Animal<BearDef>)bear).getDef(); // Works
}
}
Why does getDef require a Bear to be cast to (Animal<BearDef>) to get a BearDef? Bear is conclusively defined as extends Animal<? extends BearDef>.
[Edit] Even stranger, if I change the Bear class line:
abstract class Bear<D extends BearDef> extends Animal<BearDef> { }
(In which case D is unused and is irrelevant) it still doesn’t work. Erase D and the following line resolves the error in the code above (but doesn’t help me do what I need to do with subclass definitions):
abstract class Bear extends Animal<BearDef> { }
You’re using the raw type
Bearwhen in fact it should be parameterized with a type ofBearDef. If you wroteor
it’d work fine.
Another thing: I’m not sure how you intend to use this, but it seems likely to me that you would be fine just doing this instead:
My reason for thinking this is that if you want a
BearwhosegetDef()method returns aBlackBearDef, thatBearreference would need to be parameterized asBear<BlackBearDef>. In that case (for your example anyway) you effectively know that it’s aBlackBearfrom the declared type, so you might as well just be referring to it as aBlackBear. That said, it’s obviously not always so simple and your actual situation may not allow this.