The problem of tracing the shape

Source: Internet
Author: User
Tags inheritance

In the 6th chapter, it is known that an object can be used as its own type, or as an object of its underlying type. The behavior used to get an object handle and use it as the underlying type handle is called "tracing"-because the drawing of the inheritance tree is the base class at the top.
However, this will also encounter a problem, as shown in the following example (if you are having trouble executing this program, refer to the 3.1.2 section of chapter 3rd "assignment"):

: Music.java 
//Inheritance & upcasting
package c07;

Class Note {
  private int value;
  Private note (int val) {value = val;}
  public static final Note
    Middlec = new Note (0), 
    cSharp = new Note (1),
    Cflat = new (2);
}//ETC.
   class Instrument {public
  void Play (note N) {
    System.out.println ("Instrument.play ()");
  }

Wind objects are instruments
//because they have the same interface:
class Wind extends instrument {
  // Redefine interface method: public
  void Play (note N) {
    System.out.println ("Wind.play ()");
  }

public class Music {public
  static void tune (instrument i) {
    //...
    I.play (Note.middlec);
  }
  public static void Main (string[] args) {wind
    flute = new Wind ();
    Tune (flute); Upcasting
  }
}///:~

Where the method Music.tune () receives a instrument handle and also receives everything derived from instrument. This occurs when a wind handle is passed to tune (). There is no need for modelling at this time. This is acceptable; the interface in the instrument must exist in the wind, because wind is inherited from the instrument. The trace from wind to instrument may "shrink" the interface, but it is impossible to make it smaller than the full interface of the instrument.

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.