Subversion
Written by: Lorna Jane Mitchell
Featured Refcardz: Top Refcardz:
  1. Git
  2. DNS
  3. Data Mining
  4. Spring Data
  5. Subversion
  1. Spring Data
  2. Subversion
  3. Spring Config.
  4. Spring Annotations
  5. Data Mining

Link Details

Link 899629 thumbnail
User 855949 avatar

By bhandari4u
via javaexperience.com
Published: Jan 03 2013 / 08:22

How do covariant return types work in Java
  • 7
  • 0
  • 512
  • 855

Comments

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)