While reading on Covariant Overriding, i find out very strange fact,
covariant method overriding is implemented using a bridging technique. it also said that this feature is implemented in java5 and above.(i think it is because generics introduced from java5)
How it happens.Please help me with example.
Consider an example:
It looks good as of now. But, after type erasure, the interface loose it's generic type, and the type
T
is replaced with the upper bound. So the interface and class looks like:Now, here's the problem. The method in
Circle
after erasure is not really an overridden version ofShape
. Note that, now the methods as it looks, applies greater restriction on the parameter it takes, and the value it returns. This is because the erasure changes the signature of method in interface.To solve this issue, the compiler adds bridge method for those, which delegates the call to those actual methods in class.
So, the class is really converted to:
So, the bridge method is now the overridden version of the methods in the interface, and they delegate the call to the actual method that does the task.
Note that the type used in the bridge method is the erasure of the type parameter of the interface, in this case
Shape
.References: