Java多态

 

 

 

在Java中有两种类型的多态性:编译时多态性和运行时多态性。

编译时多态性就是指函数的重载而已,实现方法是根据函数的名字不同来调用。

 

 

运行时多态性或动态方法分派是一个过程,它对重写方法的调用在运行时体现而不是编译时(因为方法调用是由JVM不是编译器决定的,所以它被称为运行时多态性)。

在此过程中,通过超类的引用变量调用重写的方法。 要调用的方法基于引用的对象。

 

 
 1 class Super{
 2     void run() {
 3         System.out.println("SuperClass  running");
 4     }
 5 }
 6 
 7 class Child extends Super{
 8     void run() {
 9         System.out.println("Child  running");
10     }
11 
12     public static void main(String args[]) {
13         Super s = new Child ();// upcasting - 向上转换
14         s.run();
15     }
16 }

执行上面代码得到以下结果 :

Child  running
 1 class Animal {
 2     void eat() {
 3         System.out.println("eating...");
 4     }
 5 }
 6 
 7 class Dog extends Animal {
 8     void eat() {
 9         System.out.println("eating bread...");
10     }
11 }
12 
13 class Cat extends Animal {
14     void eat() {
15         System.out.println("eating rat...");
16     }
17 }
18 
19 class Lion extends Animal {
20     void eat() {
21         System.out.println("eating meat...");
22     }
23 }
24 
25 class TestPolymorphism {
26     public static void main(String[] args) {
27         Animal a;
28         a = new Dog();
29         a.eat();
30         a = new Cat();
31         a.eat();
32         a = new Lion();
33         a.eat();
34     }
35 }

 执行上面代码得到以下结果 :

eating bread...
eating rat...
eating meat...

 

上面示例中,都是有关方法被覆盖而不是数据成员,因此运行时多态性不能由数据成员实现。

如果重写数据成员,类似的代码只会输出超类数据成员。
多级继承中,覆盖方法也可以实现多态。


posted @ 2017-04-30 19:33  iiiorz  阅读(140)  评论(0编辑  收藏  举报