Let's say we have the following program:
class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
public class Main {
public static void main(String[] args) {
Fruit[] fruit = new Apple[10];
try {
fruit[0] = new Fruit(); // ArrayStoreException
fruit[0] = new Orange(); // ArrayStoreException
} catch(Exception e) { System.out.println(e); }
}
}
Based on the Java documentation:
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
I've read here that
When array is created it remembers what type of data it is meant to store.
If the array remembers what type of data it contains, it means that it KNEW the type of data it contains. But the snippet I posted is correctly compiled, so at compile time the array apparently doesn't know what type contains.
My questions are:
Why is the
ArrayStoreException
thrown only at runtime?What information are missing to the compiler to realise that that assignment is not possible?
- Is there any cases in which such code is correct so no
ArrayStoreException
is thrown?