2019-09-26 多态的使用场景

//枚举乐符类
public enum Note {
    MIDDLE_C , C_SHARP , B_FALT;
}

//乐器的基类
public class Instrument {
    public void play(Note n) {
        System.out.println("Instrument.play()");
    }
}

//乐器子类
public class Wind extends Instrument {
    public void play(Note n) {
        System.out.println("Wind.play():"+n);
    }
}

//弹奏乐器
public class Music {
    public static void tune (Instrument i) {
        i.play(Note.MIDDLE_C);
    }
    public static void main(String[] args) {
        Wind wind = new Wind();
        tune(wind);
    }
}

多态的使用点在于tune方法的参数Instrument为基类而不是导出类。
如果参数为导出类,那么会造成参数只能为某个导出类,如果有多个导出类需要调用tune(),那么每个导出类都有写一个tune()方法。如下:

public class Music {
    public static void tune (Wind w) {
        w.play(Note.MIDDLE_C);
    }
    public static void tune (Cloud w) {
        w.play(Note.MIDDLE_C);
    }
    public static void tune (Plain w) {
        w.play(Note.MIDDLE_C);
    }
    
    public static void main(String[] args) {
        Wind wind = new Wind();
        tune(wind);
        Cloud cloud = new Cloud();
        tune(cloud);
        Plain plain = new Plain();
        tune(plain);
    }
}

这样必然造成代码的冗余!

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容