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 uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?