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)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,但有人说我错了,请求各位指点!
答案为:
3)Runtime Exception
编译没问题.
这个有问题:Sub s=(Sub)b;
不能从基类cast到派生类(倒过来是可以的)
对于继承来说子类可以转换为父类,但是父类不能转换为子类Sub s = new Sub();
Base b=(Base)s;
这样就可以运行通过了
InternalFrame派生了myInternalFrame子类,其中有一段代码就跟这个类似。
InternalFrame a = MainFrame.getInstance().desk.getFrame()[1];
myInternalFrame mya = (myInternalFrame )a;但这代码执行是对的呀。