Java Reference
In-Depth Information
Listing 3-57
teaches youhowarraymanipulation canlead toan
ArrayStoreEx-
ception
:
Listing 3-57.
How an
ArrayStoreException
arises
class Point
{
int x, y;
}
class ColoredPoint extends Point
{
int color;
}
class ReificationDemo
{
public static void main(String[] args)
{
ColoredPoint[] cptArray = new ColoredPoint[1];
Point[] ptArray = cptArray;
ptArray[0] = new Point();
}
}
store one element. In contrast to this legal assignment (the types are compatible), spe-
cifying
ColoredPoint[] cptArray = new Point[1];
isillegal(andwon't
compile)becauseitwouldresultina
ClassCastException
atruntime—thearray
knows that the assignment is illegal.
Note
Ifit'snotobvious,
ColoredPoint[] cptArray = new Point[1];
is illegal because
Point
instances have fewer members (only
x
and
y
) than
Co-
loredPoint
instances(
x
,
y
,and
color
).Attemptingtoaccessa
Point
instance's
nonexistent
color
fieldfromitsentryinthe
ColoredPoint
arraywouldresultin
amemoryviolation(becausenomemoryhasbeenassignedto
color
)andultimately
crash the JVM.
The second line (
Point[] ptArray = cptArray;
) is legal because of
co-
variance
(an array of supertype references is a supertype of an array of subtype refer-