继承

来源:互联网 发布:程序员在什么系统算 编辑:程序博客网 时间:2024/05/15 13:23

What will happen if you attempt to compileand run the following code?

 

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) Compile and run without error

2) Compile time Exception

3) Runtime Exception 


第一个:可以向上转型,但不能向下转型。
如果
Sub a=new Base();
Base b=(Sub)a;
是可以的
想想:
class 动物:
class 人 extends 动物;
如果
动物 a=new 动物();
人 b=(人)a;
那么b就缺少人的部分,不能正常操作
但是
人 a=new 人();
动物 b=(动物)a;
b就指向a中的动物部分,可以正常操作

0 0