Hacker News new | ask | show | jobs
by Viliam1234 2093 days ago
Depends on whether you intend to write into the array, or only read it.

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.)