Java Reference
In-Depth Information
// we cannot be sure they will succeed; this possibility
// is suggested by the casts:
cp = (ColoredPoint)p; // p might not reference an
// object which is a ColoredPoint
// or a subclass of ColoredPoint
c = (Colorable)p; // p might not be Colorable
// The following are incorrect at compile time because
// they can never succeed as explained in the text:
Long l = (Long)p; // compile-time error #1
EndPoint e = new EndPoint();
c = (Colorable)e;
// compile-time error #2
}
}
Here, the first compile-time error occurs because the class types Long and Point are un-
related (that is, they are not the same, and neither is a subclass of the other), so a cast
between them will always fail.
The second compile-time error occurs because a variable of type EndPoint can never
reference a value that implements the interface Colorable . This is because EndPoint is a
final type, and a variable of a final type always holds a value of the same run-time type
as its compile-time type. Therefore, the run-time type of variable e must be exactly
the type EndPoint , and type EndPoint does not implement Colorable .
Example 5.5.1-2. Casting Conversion for Array Types
Click here to view code image
class Point {
int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
public String toString() { return "("+x+","+y+")"; }
}
interface Colorable { void setColor(int color); }
class ColoredPoint extends Point implements Colorable {
int color;
ColoredPoint(int x, int y, int color) {
super(x, y); setColor(color);
}
public void setColor(int color) { this.color = color; }
public String toString() {
return super.toString() + "@" + color;
}
}
class Test {
public static void main(String[] args) {
Search WWH ::




Custom Search