8.1.1 什么是多态:
1.面向对象的三大特征:封装、继承、多态。2.多态的含义:使同一个行为可以根据不同的调用对象采取不同的反应。3.实现多态的技术称为:动态绑定(dynamic binding),是指在执行期间判断所引用对象的实际类型,根据其实际的类型调用其相应的方法。4.多态存在的必要条件:4.1 类的继承4.2 方法的重写4.3 父类的引用指向子类对象(Fu fu=new Son();)5.多态的作用:消除类型之间的耦合关系
8.1.2再讨论向上转型
向上转型之后,子类的方法可能会丢失。
package com.zx.test08;enum Note {MIDDLE_E, C_SHAPP, B_FLAT;}class Instrument{public void play(Note note){//弹奏的方法System.out.println("弹奏乐器");}}class Wind extends Instrument{@Overridepublic void play(Note note) {System.out.println("Wind弹奏"+note);}public void test(){System.out.println(".........");}}public class Music {public static void tune(Instrument instrument){//instrument.test();Wind向上转为Instrument后会丢失方法instrument.play(Note.MIDDLE_E);}public static void main(String[] args) {Wind wind=new Wind();tune(wind);}}
我们可能会想,会什么要使用向上转型呢?我们也可以单独为Wind写一个Wind类型的方法?也不是不行。但是当我们需要继承的类多啦呢?那么我们就需要为没一个类去写一遍方法,不仅仅会使我们的代码繁琐,对于我们以后想要添加新的导出类就会继续写大量代码。<br /> ** 如果说我们可以只写一个以基类为参数的方法,不去管导出类,编写的代码只有导出类打交道。这一点正是多态的是使用意义**
package com.zx.test08;enum Note {MIDDLE_E, C_SHAPP, B_FLAT;}class Instrument{public void play(Note note){//弹奏的方法System.out.println("弹奏乐器");}}class Wind extends Instrument{@Overridepublic void play(Note note) {System.out.println("Wind弹奏"+note);}public void test(){System.out.println(".........");}}public class Music {public static void tune(Instrument instrument){//instrument.test();Wind向上转为Instrument后会丢失方法instrument.play(Note.MIDDLE_E);}public static void main(String[] args) {Instrument instrument=new Wind();tune(instrument);}}
