运行时多态的三原则:(应用时为覆盖)

运行时多态的三原则:(应用时为覆盖)

1、对象不变;(改变的是主观认识)

2、对于对象的调用只能限于编译时类型的方法,如调用运行时类型方法报错。

在上面的例子中:Animal a=new Dog();对象a的编译时类型为Animal,运行时类型为dog。

注意:编译时类型一定要为运行时类型的父类(或者同类型)。

对于语句:Dog d=(Dog)a。将d强制声明为a类型,此时d为Dog(),此时d就可以调用运行时类型。注意:a和d指向同一对象。

3、 在程序的运行时,动态类型判定。运行时调用运行时类型,即它调用覆盖后的方法。

 

1 package TomText;
2 //编写一个应用程序,在屏幕上显示字符串“Hello, World!”。
3   public class TomText_20 { 
4         public static void main(String args[]) { 
5             System.out.println("Hello, World!"); 
6         } 
7     }

 

 

posted @ 2018-08-04 16:51  borter  阅读(732)  评论(0编辑  收藏  举报