Covariant return types

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Aug 2006
Posts: 16
Reputation: VinC is an unknown quantity at this point 
Solved Threads: 0
VinC's Avatar
VinC VinC is offline Offline
Newbie Poster

Covariant return types

 
0
  #1
Nov 12th, 2006
I'm been working through my textbook and just can't seem to understand the section on covariant return types. ie) what are covariant return types, what they are used for, etc. The definition in the book is as follows.
An overridden method in a derived class can return a type derived from the type returned by the base-class method.
Any explanation, link to a simple tutorial or example would be greatly appreciated!

The example from the text. What is the author trying to get across?
  1. //: polymorphism/CovariantReturn.java
  2.  
  3. class Grain {
  4. public String toString() { return "Grain"; }
  5. }
  6.  
  7. class Wheat extends Grain {
  8. public String toString() { return "Wheat"; }
  9. }
  10.  
  11. class Mill {
  12. Grain process() { return new Grain(); }
  13. }
  14.  
  15. class WheatMill extends Mill {
  16. Wheat process() { return new Wheat(); }
  17. }
  18.  
  19. public class CovariantReturn {
  20. public static void main(String[] args) {
  21. Mill m = new Mill();
  22. Grain g = m.process();
  23. System.out.println(g);
  24. m = new WheatMill();
  25. g = m.process();
  26. System.out.println(g);
  27. }
  28. } /* Output:
  29. Grain
  30. Wheat
  31. *///:~
Last edited by VinC; Nov 12th, 2006 at 4:22 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 89
Reputation: TylerSBreton is an unknown quantity at this point 
Solved Threads: 3
TylerSBreton's Avatar
TylerSBreton TylerSBreton is offline Offline
Junior Poster in Training

Re: Covariant return types

 
0
  #2
Nov 12th, 2006
All it looks like that's showing you is that an object of type wheat can be stored in a grain variable, since wheat extends grain, but the proper method will be called even though the variable is of type grain.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC