面向对象编程的多态从绑定时间来看,可以分成静态多态和动态多态,也称为编译期多态和运行期多态。
java中overload是静态多态,即根据参数列表进行最佳匹配,在编译阶段决定要具体执行哪个方法。而与之相反,overriden methods则是在run-time进行动态检查。
举例说明:
1 public class UseAnimals {
2 public void doStuff(Animal a) {
3 System.out.println(“Animal”);
4 }
5 public void doStuff(Horse a) {
6 System.out.println(“Horse”);
7 }
8
9
10 }
11 class Animal{
12 public void eat()
13 {
14 }
15 }
16 class Horse extends Animal{
17 public void eat(String food) {}
18 }
19 public class TestUseAnimals {
20 public static void main(String[] args) {
21 UseAnimals ua = new UseAnimals();
22
23 Animal animalobj = new Animal();
24 Horse horseobj = new Horse();
25 Animal animalRefToHorse = new Horse();
26
27 ua.doStuff(animalobj);//Animal
28 ua.doStuff(horseobj);//Horse
29 ua.doStuff(animalRefToHorse);//Animal
30
31 }
32
33 }
可以看见UseAnimals里面有两个 doStuff方法,但参数列表不同,属于overload,在编译阶段决定执行哪个方法,毕竟参数是Animal类型还是Horse类型,这些是编译阶段就可以判断的。但引用类型具体执行哪个方法是根据静态编译阶段来决定的。比如ua.doStuff(animalRefToHorse) ,animalRefToHorse在编译阶段是判断Animal类型,所以执行doStuff(Animal a)的方法。
1 public class UseAnimals {
2 public static void main(String[] args) {
3 Animal a =new Animal();
4 a.eat();
5
6 Horse h = new Horse();
7 h.eat();
8
9 Horse ah = new Horse();
10 ah.eat();
11
12 Horse he =new Horse();
13 he.eat(“Apples”);
14
15 // Animal ah2=new Animal();
16 // ah2.eat(“Carrots”); 编译不能通过
17
18 // Animal ah2=new Horse();
19 // ah2.eat(“Carrots”); 编译不能通过
20
21
22 }
23
24
25 }
26 class Animal{
27 public void eat()
28 {
29 System.out.println(“eat”);
30 }
31 }
32 class Horse extends Animal{
33 public void eat(String food)
34 {
35 System.out.println(“eat”+food);
36 }
37 }
而override则是动态多态,执行方法是在run-time决定
1 public class UseAnimals {
2 public static void main(String[] args) {
3 // Animal a=new Animal();编译不能通过
4 Animal a=new Dog();
5 Animal b =new Cow();
6 a.vocalize();//Woof!
7 b.vocalize();//Moo!
8
9 }
10
11
12 }
13 interface Animal{
14 void vocalize();
15 }
16 class Dog implements Animal{
17 @Override
18 public void vocalize() {
19 System.out.println(“Woof!”);
20 }
21 }
22 class Cow implements Animal{
23 @Override
24 public void vocalize() {
25 System.out.println(“Moo!”);
26 }
27 }