Given the code fragment:
public static void main(String[] args) {
Short s1 = 200;
Integer s2 = 400;
Long s3 = (long) s1 + s2; // line n1
String s4 = (String) (s3 * s2); // line n2
System.out.println("Sum is " + s4);
}
What is the result?
A. Sum is 600
B. Compilation fails at line n1.
C. Compilation fails at line n2.
D. A ClassCastException is thrown at line n1.
E. A ClassCastException is thrown at line n2.
题解
line n2 的「(s3 * s2)」无法强制转型至 String 对象,原因在于数值和字符串并没有任何的继承关系,因此会发生编译错误。
至于 Wrapper 类别与基本数值数据类型在正确的类型空间大小下,可以互相转型,也能自动转型(autoboxing)。
若转型的型态和要转型的对象有继承关系,在运行阶段才会检查对象实体的型态,如果无法转型,会抛出 ClassCastException 例外。
