CONVERSIONS AND PROMOTIONS
Assignment Conversion
5.2
//
The following cause compile time errors because
//
we cannot be sure they will succeed, depending on
//
the run time type of
p
; a run time check will be
//
necessary for the needed narrowing conversion and
//
must be indicated by including a cast:
cp = p;
// p
might be neither a
ColoredPoint
//
nor a subclass of
ColoredPoint
c = p;
// p
might not implement
Colorable
}
}
Here is another example involving assignment of array objects:
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 ( 20.8) other than
Object
. An array can be assigned only to a
variable of a compatible array type, or to a variable of type
Object
.
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 variable of type
Point
. The subsequent assignment of the new
Point
to a
component of
pvec
then would throw an
ArrayStoreException
(if the pro
gram were otherwise corrected so that it could be compiled), because a
ColoredPoint
array can't have an instance of
Point
as the value of a com
ponent.
65
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved