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

被折叠的 条评论
为什么被折叠?



