90 lines
2.1 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// interfaces/music5/Music5.java
2015-11-14 16:18:05 -08:00
// <20>2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2015-06-15 17:47:35 -07:00
// Interfaces.
package interfaces.music5;
import polymorphism.music.Note;
interface Instrument {
// Compile-time constant:
int VALUE = 5; // static & final
// Cannot have method definitions:
void play(Note n); // Automatically public
void adjust();
}
class Wind implements Instrument {
@Override
public void play(Note n) {
2015-11-03 12:00:44 -08:00
System.out.println(this + ".play() " + n);
2015-06-15 17:47:35 -07:00
}
@Override
public String toString() { return "Wind"; }
@Override
2015-11-03 12:00:44 -08:00
public void adjust() { System.out.println(this + ".adjust()"); }
2015-06-15 17:47:35 -07:00
}
class Percussion implements Instrument {
@Override
public void play(Note n) {
2015-11-03 12:00:44 -08:00
System.out.println(this + ".play() " + n);
2015-06-15 17:47:35 -07:00
}
@Override
public String toString() { return "Percussion"; }
@Override
2015-11-03 12:00:44 -08:00
public void adjust() { System.out.println(this + ".adjust()"); }
2015-06-15 17:47:35 -07:00
}
class Stringed implements Instrument {
@Override
public void play(Note n) {
2015-11-03 12:00:44 -08:00
System.out.println(this + ".play() " + n);
2015-06-15 17:47:35 -07:00
}
@Override
public String toString() { return "Stringed"; }
@Override
2015-11-03 12:00:44 -08:00
public void adjust() { System.out.println(this + ".adjust()"); }
2015-06-15 17:47:35 -07:00
}
class Brass extends Wind {
@Override
public String toString() { return "Brass"; }
}
class Woodwind extends Wind {
@Override
public String toString() { return "Woodwind"; }
}
public class Music5 {
// Doesn't care about type, so new types
// added to the system still work right:
static void tune(Instrument i) {
// ...
i.play(Note.MIDDLE_C);
}
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
*/