Java Generics - An Issue with Type Erasure? -
i have generic class, codominantpopulation
, subclass of generic class, sexualpopulation
, subclass of generic class (population
). aforementioned classes defined follows:
public class codominantpopulation<o extends codominantorganism> extends sexualpopulation<o> { public codominantpopulation(list<o> organisms) { super(organisms); } ... } public class sexualpopulation<o extends sexualorganism> extends population<o> { public sexualpopulation(list<o> organisms){ super(organisms); } ... }
the codominiantorganism
above subclass of sexualorganism
, subclass (as may expected) of organism
. within codominantpopulation
, call function available codominantorganisms
, called follows:
// in codominantpopulation (o organism : population){ // organism must codominantorganism codominantgenotype.dominance dominance = organism.gettraitdominance(trait); ... }
nonetheless, runtime throws:
exception in thread "main" java.lang.classcastexception: sexualorganism cannot cast util.codominantorganism @ codominantpopulation.countdominance(codominantpopulation.java:xx) ...
i not sure how interpret/fix error. have done research , seems though related java's type erasure - possible? passing objects of type codominantorganism
codominantpopulation
before program compiled.
edit: definition population
follows:
public class population<o extends organism> { list<o> population; public population(list<o> organisms){ this.population = new arraylist<>(); this.population.addall(organisms); } ... }
my guess is less issue generic types, inheritance, based on passing not yet ready object super. maybe have factory methods or constructors try pass not yet made codominantorganism
.
this can happen several ways.
class (x y) { f(y); } protected void f(x x) { } class b b (x y) { super(y); f(y); } @override protected void f(x x) { }
here in a's constructor indeed b's f called, unready b.
with bit of luck ide warns using non-final methods in constructor, other patterns of same kind possible. maybe use findbugs checking code inconsistencies.
i might wrong, generic types not seem culprit.
Comments
Post a Comment