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.   

    class A {
    }class B extends A {
    }class C extends A {
    }
    //JDK6
    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;//编译不通过
            y = (B) x;//编译通过并可以运行,如果B存在A没有的方法时,并调用该方法时就出出现 runtime exeption
            z = (C) y;//编译不通过
            y = (A) y;//编译不通过    }
    }