Pergunta

I'd like to ask about java type erasure rules.

If we have classes:

public class Shape{}
public class Circle extends Shape{}


public class Base<T extends Shape>{
    T x;
    public void setX(T t){}
}

public class MainClass(){
    public static void main(String... _arg){
         Base<? extends Shape> bs = new Base<Circle>(); 
         bs.setX(new Circle()); // <- compilation problem
    }
}

Can you please explain me why calling setX() method causes compilation problem?

Foi útil?

Solução

Because the compiler doesn't know that new Circle is valid. Consider this code:

Base<? extends Shape> bs = new Base<Square>();  // Really a Base<Square> 
bs.setX(new Circle());

(FYI, a very similar example is given in the Java tutorial on wildcards.)

You may now exclaim "But the compiler can see it's really a Base<Square>!". But not in general. Consider this:

Base<? extends Shape> bs = someInterface.getBaseOfSomeKindOfShape();
bs.setX(new Circle());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top