What are Co-variant return types in Java
Co-variant data types are associated with using the generic type to refer to the concrete type. Sample source code showing the use of Map as co-variant return type follows:
package com.example;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class Foo{
public Map getMap() {
System.out.println("Foo");
return new HashMap();
}
public static void main(String[] args) {
Foo f = new Bar();
f.getMap();
}
}
class Bar extends Foo{
public HashMap getMap() {
System.out.println("Bar");
return new LinkedHashMap();
}
}
Output:
Bar
In the above code, both version of getMap method specify return type as Map and return instances of HashMap and LinkedHashMap.
One important point to note about co-variant data types in Java is that two methods with same name, arguments can’t be differentiated based on return types. There was a bug related to introspection of bean which caused issues with IoC containers. This bug has been fixed in JDK 1.7. Do read this interesting story on bean-introspection.
Co-variant return types is not a big concept and almost every intermediate developer in Java knows about it. But still if you have understanding the concept then do leave a comment regarding the same.





