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 public interface Instrument2 {
10 // Cannot have method definitions:
11 void play(int n); // Automatically public
14 class Wind implements Instrument,Instrument2 {
16 public void play(int n) {
17 System.out.println("Wind.play() " + n);
19 public String what() { return "Wind"; }
20 public void adjust() { System.out.println("Wind.adjust()"); }
23 class Percussion implements Instrument,Instrument2 {
25 public void play(int n) {
26 System.out.println("Percussion.play() " + n);
28 public String what() { return "Percussion"; }
29 public void adjust() { System.out.println("Percussion.adjust()"); }
32 class Stringed implements Instrument,Instrument2 {
34 public void play(int n) {
35 System.out.println("Stringed.play() " + n);
37 public String what() { return "Stringed"; }
38 public void adjust() { System.out.println("Stringed.adjust()"); }
41 class Brass extends Wind {
43 public String what() { return "Brass"; }
46 class Woodwind extends Wind {
48 public String what() { return "Woodwind"; }
51 public class InterfaceTest {
52 public InterfaceTest(){}
54 // Doesn’t care about type, so new types
55 // added to the system still work right:
56 static void tune(Instrument i) {
60 static void tuneAll(Instrument[] e) {
61 for(int k = 0; k < e.length; k++) {
66 static void tune2(Instrument2 i) {
70 static void tuneAll2(Instrument2[] e) {
71 for(int k = 0; k < e.length; k++) {
76 public static void main(String[] args) {
77 // Upcasting during addition to the array:
78 Instrument[] orchestra = new Instrument[5];
79 orchestra[0] = new Wind();
80 orchestra[1] = new Percussion();
81 orchestra[2] = new Stringed();
82 orchestra[3] = new Brass();
83 orchestra[4] = new Woodwind();
85 Instrument2[] orchestra2 = new Instrument2[5];
86 orchestra2[0] = new Wind();
87 orchestra2[1] = new Percussion();
88 orchestra2[2] = new Stringed();
89 orchestra2[3] = new Brass();
90 orchestra2[4] = new Woodwind();
95 Percussion.play() MIDDLE_C
96 Stringed.play() MIDDLE_C
97 Wind.play() MIDDLE_C //Brass.play() MIDDLE_C
98 Wind.play() MIDDLE_C //Woodwind.play() MIDDLE_C