| |
现在让我们用不同的眼光来看看本章的头一个例子。在下面这个程序中,方法play()的接口会在被覆盖的过程中发生变化。这意味着我们实际并没有“覆盖”方法,而是使其“过载”。编译器允许我们对方法进行过载处理,使其不报告出错。但这种行为可能并不是我们所希望的。下面是这个例子: //: 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! } } ///:~ 这里还向大家引入了另一个易于混淆的概念。在instrumentx中,play()方法采用了一个int(整数)数值,它的标识符是notex。也就是说,即使notex是一个类名,也可以把它作为一个标识符使用,编译器不会报告出错。但在windx中,play()采用一个notex句柄,它有一个标识符n。即便我们使用“play(notex notex)”,编译器也不会报告错误。这样一来,看起来就象是程序员有意覆盖play()的功能,但对方法的类型定义却稍微有些不确切。然而,编译器此时假定的是程序员有意进行“过载”,而非“覆盖”。请仔细体会这两个术语的区别。“过载”是指同一样东西在不同的地方具有多种含义;而“覆盖”是指它随时随地都只有一种含义,只是原先的含义完全被后来的含义取代了。请注意如果遵守标准的java命名规范,自变量标识符就应该是notex,这样可把它与类名区分开。 在tune中,“instrumentx i”会发出play()消息,同时将某个notex成员作为自变量使用(middle_c)。由于notex包含了int定义,过载的play()方法的int版本会得到调用。同时由于它尚未被“覆盖”,所以会使用基础类版本。 输出是: instrumentx.play()
|
|