当前位置:课程学习>>第四章 面向对象基础>>文本学习>>知识点五
Java实现运行时多态性的基础是动态方法调度,即方法调用时的绑定,绑定就是将一个方法调用同一个方法主体关联起来。在C语言中,方法(在C中称为函数)的绑定是由编译器来实现的,称为前期绑定(early binding),Java中是在运行时而不是在编译期绑定,通常叫做运行时绑定(run-time binding)或后期绑定。
【例4.30】运行时多态。
1 //Polymorphism.java
2 class Parents
3 {
4 void prt()
5 {
6 System.out.println("This is parents.");
7 }
8 }
9 class Father extends Parents
10 {
11 void prt()
12 {
13 System.out.println("This is father.");
14 }
15 }
16 class Mother extends Parents
17 {
18 void prt()
19 {
20 System.out.println("This is mother.");
21 }
22 }
23 public class Polymorphism
24 {
25 void judge(Parents p)
26 {
27 p.prt();
28 }
29 public static void main(String[] args)
30 {
31 Polymorphism test=new Polymorphism();
32 Parents p=new Parents();
33 Father f=new Father();
34 Mother m=new Mother();
35 //Parents f=new Father();
36 //Parents m=new Mother();
37 test.judge(p);
38 test.judge(f);
39 test.judge(m);
40 }
41 }
编译运行该程序,运行结果为:
This is parents.
This is father.
This is mother.
尽管judge方法的参数为父类的引用,实际调用时采用子类引用,由于程序在运行时进行了绑定,所以会调用相应子类中重写后的方法,而不是直接调用父类中的方法。这里还可以第33行和第34行更换为第35行和第36行,程序的输出结果不会有任何变化。