I am reading Item 28 of Effective java, in which author writes
The second major difference between arrays and generics is that arrays are reified [JLS, 4.7]. This means that arrays know and enforce their element type at runtime.
but why at runtime ? For example, consider two classes where A is the parent of B
public static void main(String[] args) {
A[] array = new B[10];
array[0] = new A();
}
This code throws an ArrayStoreException. To me, it seems that error could have been identified by the compiler. So why did the compiler let it pass. Is it because JLS doesn't want the compiler to be that smart (slow)?.
JLS 10.5 For an array whose type is A[], where A is a reference type, an assignment to a component of the array is checked at run time to ensure that the value being assigned is assignable to the component.
Now my understanding is that
- At compile time(and also at runtime) array variable in above example has type A[]
- Compiler's duty is to make sure that only A[] or some subtype of A[] is assigned to array variable.
- Same goes with components of array (array[0]), compiler will only check if the value being assigned is A or some subtype of A.
Why doesn't the compiler take into account the actual array object (B[10]) when A() is assigned to array[0]. is it because the compiler doesn't have that information available to it ?