多态的意义:改善代码的可读性并且使得程序“可扩展”
多态方法调用允许一种类型表现出与其他相似类型之间的"区别",基于方法的行为不同而表现出来
将一个方法调用同一个方法主体关联起来称作绑定,程序执行前绑定称为前期绑定,运行时根据对象的类型进行绑定称为后期绑定。
Java中除了static和final(包括private)方法,都采用后期绑定。
向上转型可以表现为此语句:(在调用方法时总是会进行正确的调用,也即调用正确的子类的方法)
(Shape类是Circle类的基类)Shape s = new Circle();
调用方法:s.draw();(draw()方法已经在Circle类中被覆写)实际上调用的还是Circle.draw(),虽然对象s被声明为Shape(但是指向Circle类的引用)
1 package Music; 2 enum Note{ 3 MIDDLE_C,C_SHARP,B_FLAT 4 } 5 class Instrument{ 6 void play(Note n) { 7 System.out.print("Instrument.play()" + n); 8 } 9 }; 10 class Percussion extends Instrument{ 11 void play(Note n) { 12 System.out.print("Percussion.play()" + n); 13 } 14 }; 15 class Stringed extends Instrument{ 16 void play(Note n) { 17 System.out.print("Stringed.play()" + n); 18 } 19 }; 20 class Wind extends Instrument{ 21 void play(Note n) { 22 System.out.print("Wind.play()" + n); 23 } 24 }; 25 class Music4{ 26 static void tune(Instrument i){ 27 i.play(Note.MIDDLE_C); 28 } 29 static void tuneAll(Instrument[] e){ 30 for(Instrument i:e){ 31 tune(i); 32 } 33 } 34 public static void main(String[]args){ 35 Instrument[]orchestra={ 36 new Wind(), 37 new Percussion(), 38 new Stringed(), 39 }; 40 tuneAll(orchestra); 41 } 42 };
上述“向上引用”的缺陷是:如果覆写了private方法,那么“向上引用”的结果是调用基类的private方法