#574 – The Problem with Array Covariance
May 2, 2012 1 Comment
If we have an array of a particular base type, assignment compatibility allows us to assign any subtype to an element of the array.
// Dog[] can contain // Dogs, or sub-classes of Dogs Dog[] dogs = new Dog[3]; dogs[0] = new Dog("Lassie"); dogs[1] = new Terrier("Jack", "Crabby"); dogs[2] = new BorderCollie("Kirby", "Ball");
Notice, however, that the array is still of type Dog[].
Array covariance allows us to assign an array of a subtype of a class to a variable whose type is an array of the base type.
Dog[] dogs = new Terrier[3];
This can lead to a problem. What looks syntactically like an array of Dogs is really an array of Terriers. So if we try putting any other Dog into the array, the code will compile, but we’ll get an error at run-time.
dogs[0] = new Terrier("Jack", "Snarly"); // ok dogs[1] = new BorderCollie("Kirby", "Ball"); // Run-time error !