1 public interface Instrument {
2 // Compile-time constant:
3 int VALUE;// = 5; // static & final
4 // Cannot have method definitions:
5 void play(int n); // Automatically public
9 class Wind implements Instrument {
11 public void play(int n) {
12 System.out.println("Wind.play() " + n);
14 public String what() { return "Wind"; }
15 public void adjust() { System.out.println("Wind.adjust()"); }
18 class Percussion implements Instrument {
20 public void play(int n) {
21 System.out.println("Percussion.play() " + n);
23 public String what() { return "Percussion"; }
24 public void adjust() { System.out.println("Percussion.adjust()"); }
27 class Stringed implements Instrument {
29 public void play(int n) {
30 System.out.println("Stringed.play() " + n);
32 public String what() { return "Stringed"; }
33 public void adjust() { System.out.println("Stringed.adjust()"); }
36 class Brass extends Wind {
38 public String what() { return "Brass"; }
41 class Woodwind extends Wind {
43 public String what() { return "Woodwind"; }
46 public class InterfaceTest {
47 public InterfaceTest(){}
49 // Doesn’t care about type, so new types
50 // added to the system still work right:
51 static void tune(Instrument i) {
55 static void tuneAll(Instrument[] e) {
56 for(int k = 0; k < e.length; k++) {
61 public static void main(String[] args) {
62 // Upcasting during addition to the array:
64 Instrument[] orchestra = new Instrument[5];
65 orchestra[0] = new Wind();
66 orchestra[1] = new Percussion();
67 orchestra[2] = new Stringed();
68 orchestra[3] = new Brass();
69 orchestra[4] = new Woodwind();
74 Percussion.play() MIDDLE_C
75 Stringed.play() MIDDLE_C
76 Wind.play() MIDDLE_C //Brass.play() MIDDLE_C
77 Wind.play() MIDDLE_C //Woodwind.play() MIDDLE_C