静态类型检查与继承

来源:互联网 发布:凯聪智云软件下载 编辑:程序博客网 时间:2024/05/01 21:01

类型检查(type checking)是指确认任一表达式的类型并保证各种语句符合类型的限制规则的过程。Java是静态类型检查的语言,但是仍然需要运行期类型检查,并抛出可能的运行时异常。

Wiki:
Static type-checking is the process of verifying the type safety of a program based on analysis of a program's source code.
Dynamic type-checking is the process of verifying the type safety of a program at runtime

package typeSystem;import static tips.Print.*;//pln()class Sup{    Sup me() { return this;}     public void inSup() {pln("Sup");}}class Sub extends Sup {    public void inSub() {pln("Sub");}}
①"new Sub().me()"返回的是什么?

A: 返回的对象实际类型Sub,声明类型Sup。编译器只知道me()在Sup中返回Sup,运行时子类继承me()并返回this。

② new Sub().me().inSub(); 为什么编译错误?

A:“子类扩展的丧失”。编译器只知道new Sub().me()为Sup类型,而Sup中没有子类特定的方法。

new Sub().me() 现在只能够调用.inSup()。

((Sub)new Sub().me()).inSub(); //可以向下造型

③假设Sub2 extends Sup,有方法 inSub2。((Sub2)new Sub().me()).inSub2(); 会怎样?

A:编译合法,但是运行时抛出 java.lang.ClassCastException: typeSystem.Sub cannot be cast to typeSystem.Sub2



0 0
原创粉丝点击