“In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass.”
Since JDK 5.0 it is possible to provide covariant return types in methods of subclasses.[2] Before this release, the Java programming language was invariant with regard to method return types.
Unfortunately, covariance is not possible with method parameters. If you wish to use that, reference [1] has a good explanation of how to do this using Generics.
Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class Animal | |
{ | |
public abstract Food eats(); | |
} | |
public abstract class Food{} | |
public class Grass extends Food | |
{ | |
public Grass() {} | |
@Override | |
public String toString() | |
{ | |
return "grass"; | |
} | |
} | |
public class Meat extends Food | |
{ | |
public Meat() {} | |
@Override | |
public String toString() | |
{ | |
return "meat"; | |
} | |
} | |
public class Cow extends Animal | |
{ | |
@Override | |
public Grass eats() | |
{ | |
return new Grass(); | |
} | |
@Override | |
public String toString() | |
{ | |
return "cow"; | |
} | |
} | |
public class Lion extends Animal | |
{ | |
@Override | |
public Meat eats() | |
{ | |
return new Meat(); | |
} | |
@Override | |
public String toString() | |
{ | |
return "lion"; | |
} | |
} |
Scala
In Scala all three are possible, contravariant, covariant and invariant for both method parameters as well as method return types. It is used fairly frequently.For more information, the blog in [3] has some excellent explanation.
References
- [1] Covariant Parameter Types
- https://www.java-tips.org/java-se-tips-100019/24-java-lang/482-covariant-parameter-types.html
- [2] Wikipedia - Covariant return type
- http://en.wikipedia.org/wiki/Covariant_return_type
- [3] Atlassian Blogs - Covariance and Contravariance in Scala
- http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/
No comments:
Post a Comment