Java Polymorphism

本文探讨了Java中多态的概念,通过音乐应用实例展示了如何利用多态实现不同乐器类型的统一处理。介绍了多态、封装和实现隐藏等面向对象特性,以及它们在代码设计中的作用。

Polymorphism decouple what from how. Encapslation creates new data types by combining characteristics and behaviors. Implementation hiding separates the interface from the implementation by making the details private.

Polymorphism(also called dynamic binding or late binding or runtime binding) deals with decoupling in terms of types. it treats many types (derived from the same base type) as if they were one type, and a single piece of code works on all those different types equally. The polymorphic method call allows one type to express its distinction from another, similar type, as long as they're both derived from the same base type.

for instance,

enum Note.java

// polymorphism/music/Note.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Notes to play on musical instruments
package polymorphism.music;

public enum Note {
  MIDDLE_C,
  C_SHARP,
  B_FLAT; // Etc.
}
// polymorphism/music/Instrument.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package polymorphism.music;

class Instrument {
  public void play(Note n) {
    System.out.println("Instrument.play()");
  }
}
// polymorphism/music/Wind.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package polymorphism.music;

// Wind objects are instruments
// because they have the same interface:
public class Wind extends Instrument {
  // Redefine interface method:
  @Override
  public void play(Note n) {
    System.out.println("Wind.play() " + n);
  }
}
// polymorphism/music/Music.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Inheritance & upcasting
// {java polymorphism.music.Music}
package polymorphism.music;

public class Music {
  public static void tune(Instrument i) {
    // ...
    i.play(Note.MIDDLE_C);
  }

  public static void main(String[] args) {
    Wind flute = new Wind();
    tune(flute); // Upcasting
  }
}
/* Output:
Wind.play() MIDDLE_C
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/polymorphism/music/Note.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/polymorphism/music/Instrument.java

4. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/polymorphism/music/Music.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值