L. DUPRÉ BERTONI L. DUPRÉ BERTONI - 10 months ago 71
Java Question

Java generic casting

I have a generic class

and a subclass B extends
The class A have a method which returns this (so an
The problem is, if I call the method on a B object, it will return a
and I have to cast to B, but B is the same as
, isn't it ? So I shouldn't have to cast ...


If your method returns A<String> it can be an object of type B but it does not have to be!

If you have a superclass of type car and BMW extends car.

Consider a factory that creates a car. The method returns car - this can be a BMW but it does not have to be a BMW.