正在加载图片...
Thinking in Java 3Edition public static final Note MIDDLE C= new Note("Middle C") C SHARP new Note(C Sharp"), B FLAT new Note("B Flat")i / 这是一个“枚举( enumeration)”类,它创建了几个固定对象以供选 择。你不能再创建其它对象了,因为构造函数是 private的。 在接下去的程序中,Wind作为一种乐器继承了 Instrument //: c07: music: Music. java // Inheritance upcasting package c07. music import com. bruceeckel simpletest*i ublic class Music private static Test monitor new Test( public static void tune(Instrument i) 1. play(Note. MIDDLE C)i public static void main(String[] args) i Wind flute new wind()i tune(flute);// Upcasting monitor.expect(new String[] t Wind. play ( Middle C" //: c07: music: Wind. java package c07.music // Wind objects are instruments // because they have the same interface public class Wind extends Instrument i / Redefine interface method public void play (Note n) System. out. println("Wind. play()"+ n)i }///:~ Music tune()需要一个 Instrument的 reference作参数,但是它 也可以接受任何由 Instrument派生出来的 reference。当main( 未经转换就把Wind的 reference传给tune()的时候,这一切就发生 了。这是完全可以可行的——因为wind继承了 Instrument,因此它 必须实现 Instrument的接口。从Wind上传到 Instrument的时 第3页共29页 www.wgqqh.com/shhgs/tij.html emailshhgsasohu.comThinking in Java 3rd Edition 第 3 页 共 29 页 www.wgqqh.com/shhgs/tij.html email:shhgs@sohu.com public static final Note MIDDLE_C = new Note("Middle C"), C_SHARP = new Note("C Sharp"), B_FLAT = new Note("B Flat"); // Etc. } ///:~ 这是一个“枚举(enumeration)”类,它创建了几个固定对象以供选 择。你不能再创建其它对象了,因为构造函数是 private 的。 在接下去的程序中,Wind 作为一种乐器继承了 Instrument: //: c07:music:Music.java // Inheritance & upcasting. package c07.music; import com.bruceeckel.simpletest.*; public class Music { private static Test monitor = new Test(); public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); } public static void main(String[] args) { Wind flute = new Wind(); tune(flute); // Upcasting monitor.expect(new String[] { "Wind.play() Middle C" }); } } ///:~ //: c07:music:Wind.java package c07.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); } } ///:~ Music.tune( )需要一个 Instrument 的 reference 作参数,但是它 也可以接受任何由 Instrument 派生出来的 reference。当 main( ) 未经转换就把 Wind 的 reference 传给 tune( )的时候,这一切就发生 了。这是完全可以可行的——因为 Wind 继承了 Instrument,因此它 必须实现 Instrument 的接口。从 Wind 上传到 Instrument 的时
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有