I have a class with generics. I know that generic type information is stripped at runtime, but this is with a bound type. I thought that at compilation java.lang.Object
is replaced with the bound type. If I know that everything will always be at least an Animal
, then why does the compiler leave it as Object
? Is there something I'm missing that would make this work like I want? Specifically, that last for
loop in the main method has a compile-time problem.
Thanks!
public static void main( String[] args ) throws Exception {
Litter<Cat> catLitter = new Litter<>();
for( Cat cat : catLitter ) {}
Litter<Animal> animalLitter = new Litter<>();
for( Animal animal : animalLitter ) {}
Litter litter = new Litter();
for( Animal animal : litter ) {} // Type mismatch: cannot convert from element type Object to Animal
}
public class Litter<T extends Animal> implements Iterable<T>{
@Override public java.util.Iterator<T> iterator() {
return new LitterIterator();
}
class LitterIterator implements java.util.Iterator<T> {
@Override public boolean hasNext() { return false; }
@Override public T next() { return null; }
}
}
public class Animal {}
public class Dog extends Animal{}
public class Cat extends Animal{}