• Post Reply Bookmark Topic Watch Topic
  • New Topic

cavariant return type  RSS feed

 
joseph prabhu
Ranch Hand
Posts: 162
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joe here
the code for covariant return type is as below

class Grain {
public String toString() { return "Grain"; }
}
class Wheat extends Grain {
public String toString() { return "Wheat"; }
}
class Mill {
Grain process() { return new Grain(); }
}
class WheatMill extends Mill {
Wheat process() { return new Wheat(); }
}
public class covariantreturn {
public static void main(String[] args) {
Mill m = new Mill(); Grain g = m.process();
System.out.println(g);
m = new WheatMill(); g = m.process();
System.out.println(g);
}}

i understood the code and defenition. can anyone say what is the use of cavariant return type.esact use please
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joseph:
can anyone say what is the use of cavariant return type.esact use please


The only advantage is that you do not have to cast the object returned from the covariant return type methods.
In your example, prior to JDK 5, the code using the process() method in WheatMill, would have to cast the returned instance to Wheat.
Now, with covariant return types, this casting is avoided. This is yet another effort to ensure compile time type safety with JDK 5.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!