Which statements, when inserted at the indicated position in the following code, will cause a runtime exception when attempting to run the program?
class A {}
class B extends A {}
class C extends A {}
public class Q3ae4 {
  public static void main(String args[]) {
    A x = new A();
    B y = new B();
    C z = new C();
    // insert statement here
  }
}
[Select All]
[1]x = y;
[2]z = x;
[3]y = (B) x;
[4]z = (C) y;
[5]y = (A) y; [Correct Choices]
[1]  false
[2]  false
[3]  true
[4]  false
[5]  false 
现在注意是runtime exeption,所以编译必须通过,因此象(2)这种编译不通过的不必考虑。
问题:
《1》答案真的是正确的吗? 是的!只有【3】会导致一个runtimeexception.
《2》第(4)个答案编译也不能通过吗?答:是的,编译也不能通过,编译器根据hierarchy结构判断出z和y不能cast。但如果是 x=y; z=(C)x; 则编译通过,而出现runtimeexception!
我自己上机调试一下,3编译通不过啊?是答案错了吗?还是我错了?

解决方案 »

  1.   

    我的测试结果
    class A {
    }class B extends A {
    }class C extends A {
    }public class T7 {
    public static void main(String args[]) {
    A x = new A();
    B y = new B();
    C z = new C(); x = y;
    // z = x;  // z = (C)x;
    y = (B) x;
    // z = (C) y;  // z = (B) y;
    // y = (A) y; // y = (B) y
    }
    }
      

  2.   


    [1]x = y;
    [2]z = x;//编译不通过
    [3]y = (B) x;//编译通过,运行异常classcastexception
    [4]z = (C) y;//二者没有继承关系,编译不通过
    [5]y = (A) y; //编译不通过