How does covariant overriding method work?
Java 5.0 permits covariant overriding: an overriding method may have a result type that is a subtype of the method it overrides.
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.
References
A Generic Java Language Extension
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?(24745)
- What is runtime polymorphism in Java?(18328)
- How to add BASIC Authentication into HttpURLConnection?(16088)
- What is String literal pool?(14754)
- Can the run() method be called directly to start a thread?(13991)
- What does Class.forname method do?(10593)
- Can transient variables be declared as 'final' or 'static'?(10446)