I think that by "Animal[] [is] a supertype of Dog[]" you mean that Animal[42]
might in fact be a Dog
? If so, then the answer is No.
In Java, variables (including array elements) are in fact references (think pointers).
Given
type Animal is tagged null record;
type Dog is new Animal with null record;
you can of course say
type Plain_Array is array (Positive range <>) of Animal;
but then all the elements have to be Animals
.
To get dispatching in Ada, you have to have a class-wide value to dispatch on, so you could try
type Class_Array is array (Positive range <>) of Animal'Class;
but then the compiler would tell you
gnatmake -c -u -f covariant_arrays.ads
gcc -c covariant_arrays.ads
covariant_arrays.ads:8:59: unconstrained element type in array declaration
gnatmake: "covariant_arrays.ads" compilation error
(Animal
and Dog
objects aren't the same size). You could try
type Access_Array is array (Positive range <>) of access Animal'Class;
which allows you to say
AA : Access_Array := (1 => new Animal, 2 => new Dog);
but then you're left with memory management problems, because Ada doesn't do garbage collection (at least, with any of the native code compilers I'm aware of). You could save yourself a lot of grief by using Ada.Containers.Indefinite_Vectors
.
No, arrays are not covariant in Ada. The problem is with the memory. When the array is created in Ada it allocates a finite amount of space for each type of a specified object. When you attempt to add a subtype element into the supertype array the computer will not be able give the subtype the amount of space necessary. Java solves this by only holding references to the objects and object references are always the same size.
– Benoite