The Java compiler allows this because arrays are covariant in Java. Ie can say:
Superclass[] arr = new Subclass[3];
This allows you to compile code, for example, your xArr[0]= new X(); . However, the JVM will catch this error at runtime and throw an ArrayStoreException . At run time, he knows that it is indeed Y[3] and therefore cannot store X
JLS, section 4.10.3 , establishes the covariance of array types:
The following rules determine the direct supertype relationship between the Types array:
If S and T are reference types, then S []> 1 T [], if S> 1 T.
Object> 1 Object []
Cloneable> 1 Object []
java.io.Serializable> 1 Object []
If P is a primitive type, then:
This contrasts with generics that are not covariant - they are invariant. I.e.
ArrayList<Superclass> list = new ArrayList<Subclass>();
source share