|
|
|
|
|
by moonchild
2092 days ago
|
|
Huh, I'm surprised the problem is present. Presumably this is valid? Animal[] a = new Animal[2];
a[0] = new Dog();
a[1] = new Cat();
If you can upcast Cat to Animal, why can Cat[] not be converted to Animal[] in the same way? |
|
If you could make sure the array is read-only (which you can't, in Java), it would make sense to say that "Cat[]" is a subclass of "Animal[]".
The problem happens when you write. "Animal[]" means that you can put any kind of animal (not just Cat) into the array; and this is not true about "Cat[]"; therefore, "Cat[]" shouldn't be a subclass of "Animal[]".
Unfortunately, Java treats "Cat[]" as a subclass of "Animal[]", and then runtime errors can happen when you write to the array. And because of backwards compatibility, this problem is not going to go away.
Later they got it right with generics. "List<Cat>" is not a subclass of "List<Animal>". (But both of them are subclasses of "List<? extend Animal>", which means: a read-only list of Animals.)