JAVA programming ideology (4)-polymorphism (1)
Polymorphism
- In object-oriented programming languages, polymorphism is the third basic type after data abstraction and inheritance.
- Polymorphism separates interfaces and implementations from each other by separating what to do and how to do them. Polymorphism not only improves the code structure and readability, but also creates extensible programs. Further on code transformation
//: polymorphism/music/Note.java// Notes to play on musical instruments.package polymorphism.music;public enum Note { MIDDLE_C, C_SHARP, B_FLAT; // Etc.} ///:~//: polymorphism/music/Instrument.javapackage polymorphism.music;import static net.mindview.util.Print.*;class Instrument { public void play(Note n) { print("Instrument.play()"); }} ///:~ //: polymorphism/music/Wind.javapackage polymorphism.music;// Wind objects are instruments// because they have the same interface:public class Wind extends Instrument { // Redefine interface method: public void play(Note n) { System.out.println("Wind.play() " + n); }} ///:~//: polymorphism/music/Music.java// Inheritance & upcasting.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*///:~
- The Music. tune () method accepts an Instrument reference and any class exported from the Instrument. For example, if Wind is an export class of Instrument, this situation occurs when Wind references are passed to the tune () method without any type conversion. This is acceptable-because Wind inherits from Instrument, the Instrument interface must exist in Wind, and the transition from Wind to Instrument may be "reduced, but it will not be narrower than all the interfaces of Instrument. Forgot object type