Howdy ranchers,
especially Howdy, David, as this seems to be your first posting on the ranch.
So welcome to the ranch!
You came up with one of the hardest nuts to crack - really!
David (you!) asked:
Shouldn't it return the B objects x value?
That's what you would expect in the first place. But there is a thing called
synthetic bridge. It is used to assure that a covariant return is at all possible. And: no, it does not return an object of type B.
The following is not your original example, but - I am lazy and had this already filed...
Output will be:
Covariance Demo
Child
gimme an A!
The structure of the synthetic bridge is included as pseudocode above.
In order for ChildCovar to be able to return a subclass of A, it has to make a "virtual" method that returns an A and so follows the rule of returning the appropriate return type. And this returns an A type.
It must do so because the variable "mixed" is polymorphic, and of type A.
It can easily be rereferenced to an object of super type A and can therefore only accept, that the method getObject returns an A and not a B.
Proposal:
After your output line
System.out.println(c.getObject().x); try these extra lines:
A a = c.getObject();
B b = c.getObject();
and look what's happening.
That should clear your question about 5 or 6.
Note however that this synthetic-bridge-thing will only be used, if you have a polymorphic parentCovar / childCovar object as in these examples.
To prove this hang these lines:
System.out.println("\nother example:");
ChildCovar baby = new ChildCovar();
B b2 = baby.getObject();
System.out.println(b2.s);
System.out.println("b2 or not b2, this is here the question");
at the end of the main method of class Main in my example.
Next time an easier question, please
One hint still remains:
There is a code tag, when you post code
you should hit the button labeled
![]()
Doing so ensures that your indentations (TAB letters and spaces) are properly displayed.
Yours,
Bu.