L. DUPRÉ BERTONI L. DUPRÉ BERTONI - 3 months ago 8
Java Question

Java generic casting

I have a generic class

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

Answer

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.

Comments