Tuesday, 27 August 2013

Java parallel inheritance hierarchies with generics and covariant returns

Java parallel inheritance hierarchies with generics and covariant returns

Let's say I have these two inheritance hierarchies:
B extends A
BPrime extends APrime extends AbstractPrime<T extends A>
I'd also like covariant return types:
public class A {
public APrime prime() {
return new APrime();
}
}
public class B extends A {
@Override
public BPrime prime() {
return new BPrime();
}
}
So far so good.
The problem is I'd like BPrime to ultimately extend AbstractPrime<B> but
since it extends APrime it ultimately extends AbstractPrime<A>.
I can make APrime and BPrime generic, but then I lose covariant return types:
public class A {
public APrime<A> prime() {
return new APrime();
}
}
public class B extends A {
@Override
public BPrime<B> prime() { // COMPILE ERROR: BPrime extends APrime
but can't
return new BPrime(); // substitute <B> for <A>
}
}
Everything works if I return a bound wildcard but there's disadvantages
associated with that and I wouldn't be able to call a particular setter on
AbstractPrime.
Another idea I had is to make A and B themselves generic.
public class A<T extends A> { ... }
public class B<T extends B> extends A<T> { ... }
In this project A and B represent entities and there's tons of them and I
think this will get messy (plus, we're using Hibernate and Spring Data and
I don't think they'll know about about the entity's generics).
Is there any way to:
keep covariant returns
not use generics on A and B
not have prime() return a bound wildcard
and have BPrime ultimately extend AbstractPrime<B> instead of
AbstractPrime<A>
Note: the prime classes are generated code, but I have control over the
code that does the generating.

No comments:

Post a Comment