By bhandari4u
via javaexperience.com
Published: Jan 03 2013 / 08:22
How do covariant return types work in Java
| Subversion | |
| Written by: Lorna Jane Mitchell | |
| Featured Refcardz: Top Refcardz: | |
| 150+ Refcardz Available · Get them all | |
By bhandari4u
via javaexperience.com
Published: Jan 03 2013 / 08:22
Comments
htowninsomniac replied ago:
This is not a correct explanation of covariant return types. class A { } class B extends A { } class C { A get() { return new A(); } } class D extends C { B get() { return new B(); } } This is an example of covariant return types: Even though the method in class C says that the return type of the method get() should be A, it is allowed to narrow the return type to B in the class D. The return types are covariant, because the relationship between A and B is in the same direction as between C and D: A is the superclass of B, and C is the superclass of D.
Sandeep Bhandari replied ago:
@htowninsomniac Thanks for noting that. The code got posted from one of my another tutorial. I have corrected it. In your code example, we can even return any instance of type B (any sub type) in the method in class D. I am wondering why no one noticed it till now!!
Voters For This Link (6)
Voters Against This Link (0)