Originally posted by Gordy Bone:
Remko,
Many thanks for your reply.
I get the polymorphic invocation issue the instance variable issue.
The thing I'm struggling with is, given that it's a B object that's returned by the method that's actually called at runtime (i.e. Y's getObject()), why is this an A?
If you take a look at the methods created in the bytecode, you can see a little better what is happening.
Notice that in the Y class, there are two methods listed with name getObject, one with return type B, and one with return type A.
In previous versions of
Java, an overridding method had to have the same return type as the overridden method.
But now with covariant returns, you can modify the return type.
So what's happened is that an extra method has been inserted into Y that has return type A. This method is called a bridge method and simply invokes the overridden method in B.
The bridge method only becomes important when the type of reference used to invoke the overridden method is a superclass reference.
Since the reference type is X, and X defines a method called getObject with return type A, the bridge method in Y, which also has return type A, is used to call the overridden method.
So the overridden method is still called, but its called through a method with return type A, so that is why the object returned from getObject has reference type A.