96 lines
2.3 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// polymorphism/music3/Music3.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// An extensible program
2016-07-28 12:48:23 -06:00
// {java polymorphism.music3.Music3}
2015-06-15 17:47:35 -07:00
package polymorphism.music3;
import polymorphism.music.Note;
class Instrument {
2015-12-02 09:20:27 -08:00
void play(Note n) {
System.out.println("Instrument.play() " + n);
}
2015-06-15 17:47:35 -07:00
String what() { return "Instrument"; }
2015-12-02 09:20:27 -08:00
void adjust() {
System.out.println("Adjusting Instrument");
}
2015-06-15 17:47:35 -07:00
}
class Wind extends Instrument {
@Override void play(Note n) {
2015-12-02 09:20:27 -08:00
System.out.println("Wind.play() " + n);
}
@Override String what() { return "Wind"; }
@Override void adjust() {
2015-12-02 09:20:27 -08:00
System.out.println("Adjusting Wind");
}
2015-06-15 17:47:35 -07:00
}
class Percussion extends Instrument {
@Override void play(Note n) {
2015-12-02 09:20:27 -08:00
System.out.println("Percussion.play() " + n);
}
@Override String what() { return "Percussion"; }
@Override void adjust() {
2015-12-02 09:20:27 -08:00
System.out.println("Adjusting Percussion");
}
2015-06-15 17:47:35 -07:00
}
class Stringed extends Instrument {
@Override void play(Note n) {
2015-12-02 09:20:27 -08:00
System.out.println("Stringed.play() " + n);
}
@Override String what() { return "Stringed"; }
@Override void adjust() {
2015-12-02 09:20:27 -08:00
System.out.println("Adjusting Stringed");
}
2015-06-15 17:47:35 -07:00
}
class Brass extends Wind {
@Override void play(Note n) {
2015-12-02 09:20:27 -08:00
System.out.println("Brass.play() " + n);
}
@Override void adjust() {
2015-12-02 09:20:27 -08:00
System.out.println("Adjusting Brass");
}
2015-06-15 17:47:35 -07:00
}
class Woodwind extends Wind {
@Override void play(Note n) {
2015-12-02 09:20:27 -08:00
System.out.println("Woodwind.play() " + n);
}
@Override String what() { return "Woodwind"; }
2015-06-15 17:47:35 -07:00
}
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);
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C
2015-09-07 11:44:36 -06:00
*/