84 lines
2.0 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: polymorphism/music3/Music3.java
2015-05-29 14:18:51 -07:00
// <20>2015 MindView LLC: see Copyright.txt
2015-04-20 15:36:01 -07:00
// An extensible program.
package polymorphism.music3;
import polymorphism.music.Note;
import static net.mindview.util.Print.*;
class Instrument {
void play(Note n) { print("Instrument.play() " + n); }
String what() { return "Instrument"; }
void adjust() { print("Adjusting Instrument"); }
}
class Wind extends Instrument {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void play(Note n) { print("Wind.play() " + n); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
String what() { return "Wind"; }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void adjust() { print("Adjusting Wind"); }
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
class Percussion extends Instrument {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void play(Note n) { print("Percussion.play() " + n); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
String what() { return "Percussion"; }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void adjust() { print("Adjusting Percussion"); }
}
class Stringed extends Instrument {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void play(Note n) { print("Stringed.play() " + n); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
String what() { return "Stringed"; }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void adjust() { print("Adjusting Stringed"); }
}
class Brass extends Wind {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void play(Note n) { print("Brass.play() " + n); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void adjust() { print("Adjusting Brass"); }
}
class Woodwind extends Wind {
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
void play(Note n) { print("Woodwind.play() " + n); }
2015-05-05 11:20:13 -07:00
@Override
2015-04-20 15:36:01 -07:00
String what() { return "Woodwind"; }
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -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);
2015-05-18 23:05:20 -07:00
}
2015-04-20 15:36:01 -07:00
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);
}
} /* Output:
Wind.play() MIDDLE_C
Percussion.play() MIDDLE_C
Stringed.play() MIDDLE_C
Brass.play() MIDDLE_C
Woodwind.play() MIDDLE_C
*///:~