Why can an instance of a superclass be placed in an array of a subclass?

Suppose we have 2 classes:

class X { } class Y extends X { } 

Create an array in the main function:

 Y[] yArr = new Y[3] // created Y class objects array X[] xArr = yArr; xArr[0]= new X() // VALID. WHY? 

How can it be? Since xArr refers to the object Y[] , and for my understanding, it cannot create an object X.

+6
source share
1 answer

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:

    • Object> 1 P []

    • Cloning> 1 P []

    • java.io.Serializable> 1 P []

This contrasts with generics that are not covariant - they are invariant. I.e.

 ArrayList<Superclass> list = new ArrayList<Subclass>(); // doesn't compile. 
+9
source

Source: https://habr.com/ru/post/956896/


All Articles