84 lines
2.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// polymorphism/music3/Music3.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-06-15 17:47:35 -07:00
// An extensible program.
package polymorphism.music3;
import polymorphism.music.Note;
class Instrument {
2015-11-03 12:00:44 -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-11-03 12:00:44 -08:00
void adjust() { System.out.println("Adjusting Instrument"); }
2015-06-15 17:47:35 -07:00
}
class Wind extends Instrument {
@Override
2015-11-03 12:00:44 -08:00
void play(Note n) { System.out.println("Wind.play() " + n); }
2015-06-15 17:47:35 -07:00
@Override
String what() { return "Wind"; }
@Override
2015-11-03 12:00:44 -08:00
void adjust() { System.out.println("Adjusting Wind"); }
2015-06-15 17:47:35 -07:00
}
class Percussion extends Instrument {
@Override
2015-11-03 12:00:44 -08:00
void play(Note n) { System.out.println("Percussion.play() " + n); }
2015-06-15 17:47:35 -07:00
@Override
String what() { return "Percussion"; }
@Override
2015-11-03 12:00:44 -08:00
void adjust() { System.out.println("Adjusting Percussion"); }
2015-06-15 17:47:35 -07:00
}
class Stringed extends Instrument {
@Override
2015-11-03 12:00:44 -08:00
void play(Note n) { System.out.println("Stringed.play() " + n); }
2015-06-15 17:47:35 -07:00
@Override
String what() { return "Stringed"; }
@Override
2015-11-03 12:00:44 -08:00
void adjust() { System.out.println("Adjusting Stringed"); }
2015-06-15 17:47:35 -07:00
}
class Brass extends Wind {
@Override
2015-11-03 12:00:44 -08:00
void play(Note n) { System.out.println("Brass.play() " + n); }
2015-06-15 17:47:35 -07:00
@Override
2015-11-03 12:00:44 -08:00
void adjust() { System.out.println("Adjusting Brass"); }
2015-06-15 17:47:35 -07:00
}
class Woodwind extends Wind {
@Override
2015-11-03 12:00:44 -08:00
void play(Note n) { System.out.println("Woodwind.play() " + n); }
2015-06-15 17:47:35 -07:00
@Override
String what() { return "Woodwind"; }
}
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
*/