In trying to structure my classes in a logical way, I discovered Java's ability to do recursive generics. It is almost exactly what I was looking for structure-wise, but I ran into a problem with abstract classes. I think Foo and Bar would be extremely confusing for this example, so I've named my classes relating to my actual project.
public abstract class GeneCarrier<T extends GeneCarrier<T>> {
protected Gene<T> gene;
//...
}
public class Gene<T extends GeneCarrier<T>> {
//...
}
public abstract class Organism extends GeneCarrier<Organism>{
//...
}
public class Human extends Organism {
public void foo(){
Gene<Human> g; // Bound mismatch: The type Human is not a valid substitute for the bounded parameter <T extends GeneCarrier<T>> of the type Gene<T>
}
}
I thought that the problem might be with the definition of my abstract Organism
class, but this also produced a similar error:
public abstract class Organism extends GeneCarrier<? extends Organism>{
//...
}
Is there an inherent problem in trying to use an abstract class with recursive template definitions, or have I made a mistake in the class definitions?