Java 5.0 permits covariant overriding: an overriding method may have a result type that is a subtype of the method it overrides.
Click below links to know more
class A { int x = 5; } class B extends A { int x = 6; } class CovariantObj { public A getObject() { System.out.println("In A"); return new A(); } } class SubCovariantObj extends CovariantObj { public B getObject() { System.out.println("In B"); return new B(); } public static void main(String[] args) { CovariantObj c = new SubCovariantObj(); System.out.println(c.getObject().x); } }
The output is
In B 5
Why the output of above code is 5 after printing "In B"? The c.getObjec() returns an instance of B class.
To make overriding works properly for covariant overriding case, Java compiler inserts a synthetic bridge method that is A getObject() method into the SubCovariantObj class. The bridge method only is encoded directly in JVM byte code. For example, the JVM byte code is similar to the following code:
class SubCovariantObj extends CovariantObj { public B getObject() { System.out.println("In B"); return new B(); } public A getObject() { return this.getObject(); } ... }
Apparently what's happening is that when the runtime type of the object is SubCovariantObj, a call to getObject() still invokes the overridden method by polymorphism, but if the reference type is CovariantObj, then the call is made through the bridge method, and so the return type in that case is A. We know that accessing a field (data member) of an object is determined by the type of reference not the current instance class holded by the reference. That is why it prints out 5.
Click below links to know more
Comments
Post a Comment