Java Reference
In-Depth Information
try {
pa[0] = new Point();
} catch (ArrayStoreException e) {
System.out.println(e);
}
}
}
This program produces the output:
true
java.lang.ArrayStoreException: Point
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 com-
pile 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 assign-
ment is valid only if the type of the value assigned at run time is, more specifically, a
ColoredPoint
.
The Java Virtual Machine checks for such a situation at run time to ensure that the
assignment is valid; if not, an
ArrayStoreException
is thrown.
10.6. Array Initializers
array creation expression (§
15.10
), to create an array and provide some initial values.
ArrayInitializer:
{
VariableInitializers
opt
,
opt
}
VariableInitializers:
VariableInitializer
VariableInitializers
,
VariableInitializer
The following is repeated from §
8.3
to make the presentation here clearer: