If an array variable v has type A[]
, where A is a reference type, then v can hold a
reference to an instance of any array type B[]
, provided B can be assigned to A.
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test { public static void main(String[] args) { ColoredPoint[] cpa = new ColoredPoint[10]; Point[] pa = cpa; System.out.println(pa[1] == null); try { pa[0] = new Point(); } catch (ArrayStoreException e) { System.out.println(e); } } }
true java.lang.ArrayStoreException
Here the variable pa
has type Point[]
and the variable cpa
has as its value a reference to an object of type ColoredPoint[]
. A ColoredPoint
can be assigned
to a Point
; therefore, the value of cpa
can be assigned to pa
.
A reference to this array pa
, for example, testing whether pa[1]
is null
, will not result in a run-time type error. This is because the element of the array of type ColoredPoint[]
is a ColoredPoint
, and every ColoredPoint
can stand in for a Point
, since Point
is the superclass of ColoredPoint
.
On the other hand, an assignment to the array pa
can result in a run-time error. At compile time, an assignment to an element of pa
is checked to make sure that the value assigned is a Point
. But since pa
holds a reference to an array of ColoredPoint
, the assignment is valid only if the type of the value assigned at run-time is, more specifically, a ColoredPoint
.
Java checks for such a situation at run-time to ensure that the assignment is valid; if not, an ArrayStoreException
is thrown. More formally: an assignment to an element of an array whose type is A[]
, where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.
At length burst in the argent revelry,
With plume, tiara, and all rich array . . .
John Keats, The Eve of St. Agnes (1819)