I'm currently studying java generic by following the book "java generics and collection by Maurice Naftalin 2006".
In the section covariant overriding on return type, the author stated
Could someone please explain to me, what does the implementation, i.e. the code inside the bridge method would look like? Does the bridge method call the original method (i.e. method with signature public Point clone()
)?
I advise you to refer to Oracle material about it and to make some tests to understand the bridge mechanism.
Bridge is an artifact to go beyond the overriding method ability that was invariant at compile time before Java 1.5.
Java 1.5 supports covariant return types. What does this mean? Before 1.5, when you override a superclass method, the name, argument types and return type of the overrding method has to be exactly same as that of superclass method. Overriding method is said to be invariant with respect to argument types and return type.
If you change any argument type, then you are not really overriding a method -- you are actually overloading it.
The bridge is a bridge : so it makes a link. Here it is between the method with the original return type and the overrided method with the covariant return type.
So yes you are right.
You want to check that ? Compile the class and then disassemble the source code of it.
$ javap -c Point.class
You will get something like :
Compiled from "Point.java" public class Point { public Point(int, int); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":()V 4: aload_0 5: iload_1 6: putfield #2 // Field x:I 9: aload_0 10: iload_2 11: putfield #3 // Field y:I 14: return protected Point clone() throws java.lang.CloneNotSupportedException; Code: 0: new #4 // class Point 3: dup 4: aload_0 5: getfield #2 // Field x:I 8: aload_0 9: getfield #3 // Field y:I 12: invokespecial #5 // Method "":(II)V 15: areturn protected java.lang.Object clone() throws java.lang.CloneNotSupportedException; Code: 0: aload_0 1: invokevirtual #6 // Method clone:()LPoint; 4: areturn }
You can see the delegation between Object clone()
and Point clone()
.
Of course you cannot write such as code as return type based overloading is not allowed in Java at compile time but at runtime JVM can use this feature from compiled classes.