Java Reference
In-Depth Information
This case could slip past the compile-time checking if, for example, a referen-
ce to an array were stored in a variable of type Object .
• If T is an array type TC [] , that is, an array of components of type TC , then a run-
time exception is thrown unless one of the following is true:
TC and RC are the same primitive type.
TC and RC are reference types and type RC can be cast to TC by a recursive
application of these run-time rules for casting.
Example 5.5.3-1. Incompatible Types at Run Time
Click here to view code image
class Point { int x, y; }
interface Colorable { void setColor(int color); }
class ColoredPoint extends Point implements Colorable {
int color;
public void setColor(int color) { this.color = color; }
}
class Test {
public static void main(String[] args) {
Point[] pa = new Point[100];
// The following line will throw a ClassCastException:
ColoredPoint[] cpa = (ColoredPoint[])pa;
System.out.println(cpa[0]);
int[] shortvec = new int[2];
Object o = shortvec;
// The following line will throw a ClassCastException:
Colorable c = (Colorable)o;
c.setColor(0);
}
}
This program uses casts to compile, but it throws exceptions at run time, because the
types are incompatible.
5.6. Numeric Promotions
Numeric promotion is applied to the operands of an arithmetic operator.
Numeric promotion contexts allow the use of:
• an identity conversion (§ 5.1.1 )
• a widening primitive conversion (§ 5.1.2 )
Search WWH ::




Custom Search