This covariance is possible in C #:
IEnumerable<A> a = new List<A>(); IEnumerable<B> b = new List<B>(); a = b; ... class A { } class B : A { }
This is not possible in Java: (Iterable: This question discusses Java arrays and generalizations: Java is equivalent to C # IEnumerable <T> ).
Iterable<A> a = new ArrayList<A>(); Iterable<B> b = new ArrayList<B>(); a = b; ... class A { } class B extends A { }
With Iterable, Java Doesn't See These Two Covariance Collections
What is an iterative / enumerated interface in Java that can facilitate covariance?
Another good example of covariance, given the same class A and class B above, is allowed in both Java and C #:
A[] x; B[] y = new B[10]; x = y;
This feature is available in both languages ββfrom their version 1. It is good that they are making progress to make this a reality in generics . C # has less friction, albeit in terms of syntax.
Covariance is mandatory for all OOP languages, otherwise OOP inheritance would be a futile exercise, for example.
A x; B y = new B(); x = y;
And this power should extend to generics.
Thank you all for your reply and understanding. Now reusable with covariant Java generics. This is not the syntax that some of us require, but it ( <? extends classHere>
) certainly fits the bill:
import java.util.*; public class Covariance2 { public static void testList(Iterable<? extends A> men) { for(A good : men) { System.out.println("Good : " + good.name); } } public static void main(String[] args) { System.out.println("The A"); { List<A> team = new ArrayList<A>(); { A player = new A(); player.name = "John"; team.add(player); } { A player = new A(); player.name = "Paul"; team.add(player); } testList(team); } System.out.println("The B"); { List<B> bee = new ArrayList<B>(); { B good = new B(); good.name = "George"; bee.add(good); } { B good = new B(); good.name = "Ringo"; bee.add(good); } testList(bee); } } } class A { String name; } class B extends A {}
Conclusion:
The A Good : John Good : Paul The B Good : George Good : Ringo
If anyone is interested in how it looks in C #
using System.Collections.Generic; using System.Linq; public class Covariance2 { internal static void TestList(IEnumerable<A> men) { foreach(A good in men) { System.Console.WriteLine("Good : " + good.name); } } public static void Main(string[] args) { System.Console.WriteLine("The A"); { IList<A> team = new List<A>(); { A player = new A(); player.name = "John"; team.Add(player); } { A player = new A(); player.name = "Paul"; team.Add(player); } TestList(team); } System.Console.WriteLine("The A"); { IList<B> bee = new List<B>(); { B good = new B(); good.name = "George"; bee.Add(good); } { B good = new B(); good.name = "Ringo"; bee.Add(good); } TestList(bee); } } } class A { internal string name; } class B : A {}