JAVA programming ideology (4)-polymorphism (1)

Source: Internet
Author: User

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
      • Why did everyone deliberately forget the object type? This situation occurs during the upward transformation. It seems more intuitive if the tune () method accepts a Wind reference as its own parameter. However, this raises an important issue: If you do that, you need to write a new tune method for each type of the Instrument. In this case, when we add a new type, a large amount of code is required.
      • For example
        //: polymorphism/music/Music2.java// Overloading instead of upcasting.package polymorphism.music;import static net.mindview.util.Print.*;class Stringed extends Instrument {  public void play(Note n) {    print("Stringed.play() " + n);  }}class Brass extends Instrument {  public void play(Note n) {    print("Brass.play() " + n);  }}public class Music2 {  public static void tune(Wind i) {    i.play(Note.MIDDLE_C);  }  public static void tune(Stringed i) {    i.play(Note.MIDDLE_C);  }  public static void tune(Brass i) {    i.play(Note.MIDDLE_C);  }  public static void main(String[] args) {    Wind flute = new Wind();    Stringed violin = new Stringed();    Brass frenchHorn = new Brass();    tune(flute); // No upcasting    tune(violin);    tune(frenchHorn);  }} /* Output:Wind.play() MIDDLE_CStringed.play() MIDDLE_CBrass.play() MIDDLE_C*///:~
        • This can be done, but there is a drawback: you must write a specific type of method for adding each new Instrument class. This means that you need more programming at the beginning. At the same time, you still need to do a lot of work to add new methods like tune () or add new Classes exported from Instrument later. In addition, if we forget to reload a method, the compiler will not return any error information, so that the entire processing process about the type will become difficult to control.

        • If we only write such a simple method, it only accepts the base class as the parameter, rather than the special export class. Will the situation be better? That is to say, will it be better if the code we write only deals with the base class regardless of the existence of the export class? This is what polymorphism permits.

          Transfer
          • Observe a piece of code
            public static void tune(Instrument i) {    // ...    i.play(Note.MIDLE_C);}
            • It accepts Instrument references. In this case, how does the compiler know that this Instrument references a Wind object instead of a Brass object or others? In fact, the compiler is unknown, and this involves binding. Method call binding
              • Associating a method call with a method subject is called binding. For example, binding before the program is executed is called pre-binding. This is the default binding method in process-oriented languages. For example, C ++ only has one method call, that is, pre-binding.
              • However, this is not enough to solve the confusion of the above Code. The solution is to bind the code later. It means to bind the code according to the object type at runtime, later binding is also called dynamic binding or runtime binding. Here, the compiler never knows the object type, but the method calling mechanism can find the correct method body and call it. The later binding mechanism varies with the compilation language. In any case, a certain type of information must be placed in the object ".
              • Except for the Static method and the final method (the private method belongs to the final method), all other methods are post-bound, which means that normally, we don't have to determine whether to bind later-it will automatically happen.
              • Declaring a method as a final method will effectively "close" the dynamic binding, so that the compiler will generate more effective code for the final method call. Produce correct behavior
                • Once we know that all methods in Java are implemented by dynamic binding to realize polymorphism, we can write program code that only deals with the base class, the code can run correctly for all export classes.
                  //: polymorphism/shape/Shape.javapackage polymorphism.shape;public class Shape {  public void draw() {}  public void erase() {}} ///:~//: polymorphism/shape/Circle.javapackage polymorphism.shape;import static net.mindview.util.Print.*;public class Circle extends Shape {  public void draw() { print("Circle.draw()"); }  public void erase() { print("Circle.erase()"); }} ///:~//: polymorphism/shape/Triangle.javapackage polymorphism.shape;import static net.mindview.util.Print.*;public class Triangle extends Shape {  public void draw() { print("Triangle.draw()"); }  public void erase() { print("Triangle.erase()"); }} ///:~//: polymorphism/shape/Square.javapackage polymorphism.shape;import static net.mindview.util.Print.*;public class Square extends Shape {  public void draw() { print("Square.draw()"); }  public void erase() { print("Square.erase()"); }} ///:~//: polymorphism/shape/RandomShapeGenerator.java// A "factory" that randomly creates shapes.package polymorphism.shape;import java.util.*;public class RandomShapeGenerator {  private Random rand = new Random(47);  public Shape next() {    switch(rand.nextInt(3)) {      default:      case 0: return new Circle();      case 1: return new Square();      case 2: return new Triangle();    }  }} ///:~//: polymorphism/Shapes.java// Polymorphism in Java.import polymorphism.shape.*;public class Shapes {  private static RandomShapeGenerator gen =    new RandomShapeGenerator();  public static void main(String[] args) {    Shape[] s = new Shape[9];    // Fill up the array with shapes:    for(int i = 0; i < s.length; i++)      s[i] = gen.next();    // Make polymorphic method calls:    for(Shape shp : s)      shp.draw();  }} /* Output:Triangle.draw()Triangle.draw()Square.draw()Triangle.draw()Square.draw()Triangle.draw()Square.draw()Triangle.draw()Circle.draw()*///:~
                  • This code is a typical multi-state application. Scalability
                    • With the polymorphism mechanism, we can add any number of new types to the system as needed without modifying the code. In a Good OOP program, most or all methods only communicate with the base class interface. Such a program is extensible, because we can inherit new data types from the general base class, thus adding some new functions, the methods that operate the basic class interface can be applied to the new class without any changes.
                    • Let's take a look at the example of Instrument.
                      //: polymorphism/music3/Music3.java// An extensible program.package polymorphism.music3;import polymorphism.music.Note;import static net.mindview.util.Print.*;class Instrument {  void play(Note n) { print("Instrument.play() " + n); }  String what() { return "Instrument"; }  void adjust() { print("Adjusting Instrument"); }}class Wind extends Instrument {  void play(Note n) { print("Wind.play() " + n); }  String what() { return "Wind"; }  void adjust() { print("Adjusting Wind"); }}    class Percussion extends Instrument {  void play(Note n) { print("Percussion.play() " + n); }  String what() { return "Percussion"; }  void adjust() { print("Adjusting Percussion"); }}class Stringed extends Instrument {  void play(Note n) { print("Stringed.play() " + n); }  String what() { return "Stringed"; }  void adjust() { print("Adjusting Stringed"); }}class Brass extends Wind {  void play(Note n) { print("Brass.play() " + n); }  void adjust() { print("Adjusting Brass"); }}class Woodwind extends Wind {  void play(Note n) { print("Woodwind.play() " + n); }  String what() { return "Woodwind"; }}    public class Music3 {  // Doesn't care about type, so new types  // added to the system still work right:  public static void tune(Instrument i) {    // ...    i.play(Note.MIDDLE_C);  }  public static void tuneAll(Instrument[] e) {    for(Instrument i : e)      tune(i);  }      public static void main(String[] args) {    // Upcasting during addition to the array:    Instrument[] orchestra = {      new Wind(),      new Percussion(),      new Stringed(),      new Brass(),      new Woodwind()    };    tuneAll(orchestra);  }} /* Output:Wind.play() MIDDLE_CPercussion.play() MIDDLE_CStringed.play() MIDDLE_CBrass.play() MIDDLE_CWoodwind.play() MIDDLE_C*///:~
                      • In fact, there is no need to change the tune () method. All new classes can run correctly with the original classes, even if tune () is stored in a file separately, in addition, other new methods are added to the Instrument interface, and tune () can run correctly without writing any more.
                      • As you can see, the tune () method completely ignores the changes in the Code around it and still runs normally, which is what we expect polymorphism to have. Polymorphism is an important technology that allows programmers to "separate changed things from unchanged things.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.