What will happen if you attempt to compile and run the following code?
1)Compile and run without error
2)Compile time Exception
3)Runtime Exception
class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class CEx{
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub)b;
}
}我选择1,但有人说我错了,请求各位指点!

解决方案 »

  1.   

    如果不考虑你的中文()的话
    答案为:
    3)Runtime Exception
    编译没问题.
    这个有问题:Sub s=(Sub)b;
    不能从基类cast到派生类(倒过来是可以的)
      

  2.   

    ClassCastException
    对于继承来说子类可以转换为父类,但是父类不能转换为子类Sub s = new Sub();
    Base b=(Base)s;
    这样就可以运行通过了
      

  3.   

    我曾经写过这段代码:
    InternalFrame派生了myInternalFrame子类,其中有一段代码就跟这个类似。
    InternalFrame a = MainFrame.getInstance().desk.getFrame()[1];
    myInternalFrame mya = (myInternalFrame )a;但这代码执行是对的呀。
      

  4.   

    我今天到书店里看了java core技术书,它是这样写的,子类的值可以直接赋给超类实例这是,如果要把超类赋给子类,必须要用子类来转换,如:(子类名)val.