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
  • 842
  • 859
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.

Upvoters (6)

Downvoters (0)

    Apache Hadoop
    Written by: Piotr Krewski
    Featured Refcardz: Top Refcardz:
    1. Play
    2. Akka
    3. Design Patterns
    4. OO JS
    5. Cont. Delivery
    1. Play
    2. Java Performance
    3. Akka
    4. REST
    5. Java