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?
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With