Java Reference
In-Depth Information
Example 5.2-3. Assignment Conversion for Array Types
Click here to view code image
class Point { int x, y; }
class ColoredPoint extends Point { int color; }
class Test {
public static void main(String[] args) {
long[] veclong = new long[100];
Object o = veclong; // okay
Long l = veclong; // compile-time error
short[] vecshort = veclong; // compile-time error
Point[] pvec = new Point[100];
ColoredPoint[] cpvec = new ColoredPoint[100];
pvec = cpvec; // okay
pvec[0] = new Point(); // okay at compile time,
// but would throw an
// exception at run time
cpvec = pvec;
// compile-time error
}
}
In this example:
• The value of veclong cannot be assigned to a Long variable, because Long is a
class type other than Object . An array can be assigned only to a variable of a
compatible array type, or to a variable of type Object , Cloneable or
java.io.Serializable .
• The value of veclong cannot be assigned to vecshort , because they are arrays of
primitive type, and short and long are not the same primitive type.
• The value of cpvec can be assigned to pvec , because any reference that could
be the value of an expression of type ColoredPoint can be the value of a vari-
able of type Point . The subsequent assignment of the new Point to a compon-
ent of pvec then would throw an ArrayStoreException (if the program were oth-
erwise corrected so that it could be compiled), because a ColoredPoint array
cannot have an instance of Point as the value of a component.
• The value of pvec cannot be assigned to cpvec , because not every reference
that could be the value of an expression of type ColoredPoint can correctly be
the value of a variable of type Point . If the value of pvec at run time were a
reference to an instance of Point[] , and the assignment to cpvec were allowed,
a simple reference to a component of cpvec , say, cpvec[0] , could return a Point ,
and a Point is not a ColoredPoint . Thus to allow such an assignment would al-
Search WWH ::




Custom Search