1 //: interfaces/music4/Music4.java
2 // Abstract classes and methods.
4 abstract class Instrument {
6 private int i; // Storage allocated for each
7 public abstract void play(int n);
8 public String what() { return "Instrument"; }
9 public abstract void adjust();
12 class Wind extends Instrument {
14 public void play(int n) {
15 System.out.println("Wind.play() " + n);
17 public String what() { return "Wind"; }
18 public void adjust() {}
21 class Percussion extends Instrument {
23 public void play(int n) {
24 System.out.println("Percussion.play() " + n);
26 public String what() { return "Percussion"; }
27 public void adjust() {}
30 class Stringed extends Instrument {
32 public void play(int n) {
33 System.out.println("Stringed.play() " + n);
35 public String what() { return "Stringed"; }
36 public void adjust() {}
39 class Brass extends Wind {
41 public void play(int n) {
42 System.out.println("Brass.play() " + n);
44 public void adjust() { System.out.println("Brass.adjust()"); }
47 class Woodwind extends Wind {
49 public void play(int n) {
50 System.out.println("Woodwind.play() " + n);
52 public String what() { return "Woodwind"; }
56 public class AbstractTest {
58 public AbstractTest() {}
60 // Doesn’t care about type, so new types
61 // added to the system still work right:
62 static void tune(Instrument i) {
66 static void tuneAll(Instrument[] e) {
67 for(int k = 0; k < e.length; k++) {
72 public static void main(String[] args) {
73 // Upcasting during addition to the array:
74 Instrument[] orchestra = new Instrument[5];
75 orchestra[0] = new Wind();
76 orchestra[1] = new Percussion();
77 orchestra[2] = new Stringed();
78 orchestra[3] = new Brass();
79 orchestra[4] = new Woodwind();
84 Percussion.play() MIDDLE_C
85 Stringed.play() MIDDLE_C
87 Woodwind.play() MIDDLE_C