Now let's look at the first example of this chapter with a different perspective. In the following program, the interface of method play () will change in the process of being overwritten. This means that we actually do not have the "overlay" approach, but rather that it "overload" it. The compiler allows us to overload the method so that it does not report an error. But this kind of behavior may not be what we want. Here is the example:
: Winderror.java
//accidentally changing the interface
class Notex {public
static final int
Middle_c = 0, C_sharp = 1, C_flat = 2;
}
Class Instrumentx {public
void play (int notex) {
System.out.println ("Instrumentx.play ()");
}
Class Windx extends Instrumentx {
//oops! Changes the method interface: public
void Play (Notex n) {
System.out.println ("Windx.play (Notex N)");
}
}
public class Winderror {public
static void tune (Instrumentx i) {
//...
I.play (Notex.middle_c);
}
public static void Main (string[] args) {
windx flute = new Windx ();
Tune (flute); Not the desired behavior!
}
} ///:~
Another confusing concept has been introduced here. In Instrumentx, the Play () method takes an int (integer) value, and its identifier is Notex. That is, even if Notex is a class name, it can be used as an identifier and the compiler does not report an error. But in Windx, play () takes a Notex handle, which has an identifier n. Even if we use "Play (Notex Notex)", the compiler will not report an error. This makes it seem like the programmer intentionally overwrites play (), but the type definition of the method is somewhat imprecise. However, the compiler now assumes that the programmer is intentionally "overloaded" rather than "overwritten." Please carefully understand the difference between the two terms. "Overload" means that the same thing has many meanings in different places, while "covering" means that it has only one meaning at any time, but the original meaning is completely replaced by later meaning. Note that if you follow the standard Java naming conventions, the argument identifier should be Notex, which separates it from the class name.
In tune, "Instrumentx i" emits a play () message, while a Notex member is used as an argument (Middle_c). Because Notex contains the int definition, the int version of the overloaded Play () method is invoked. Also, because it has not been "overwritten", the base class version is used.
The output is:
Instrumentx.play ()