Link Details

Link 899629 thumbnail
User 855949 avatar

By bhandari4u
Published: Jan 03 2013 / 08:22

How do covariant return types work in Java
  • 7
  • 0
  • 825
  • 859


Add your comment
User 272422 avatar

htowninsomniac replied ago:

0 votes Vote down Vote up Reply

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.

User 855949 avatar

Sandeep Bhandari replied ago:

0 votes Vote down Vote up Reply

@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!!

Add your comment

Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.

Voters For This Link (6)

Voters Against This Link (0)

    Written by: Bert Belder
    Featured Refcardz: Top Refcardz:
    1. Design Patterns
    2. OO JS
    3. Cont. Delivery
    4. Java EE7
    5. HTML5 Mobile
    1. Debugging JavaScript
    2. OO JS
    3. JSON
    4. Ajax
    5. REST