public class Music2 {
public static void main(String[] args) {
Instrument[] inst = {
new Guitar(),
new Piano(),
new EPiano()
};
int i;
for(i = 0; i < 3; i++)
tune(inst[i]);
System.out.println("-----");
Instrument[] inst2 = new Instrument[10];
for(i = 0; i < 10; i++)
inst2[i] = randInstrument();
for(i = 0; i < 10; i++)
tune(inst2[i]);
}
static private void tune(Instrument i) {
i.play(Note.MIDDLE_C);
}
private static Instrument randInstrument() {
switch((int)(Math.random() * 4)) {
default:
case 0:
return new Guitar();
case 1:
return new Electone();
case 2:
return new Piano();
case 3:
return new EPiano();
}
}
}
class Note {
private String value;
private Note(String s) {
value = s;
}
public String toString() {
return(value);
}
public static final Note
MIDDLE_B = new Note("B"),
MIDDLE_C = new Note("C"),
C_SHARP = new Note("C#");
}
class Instrument {
public void play(Note n) {
System.out.println("Instrument.play(" + n + ")");
}
}
class Guitar extends Instrument {
public void play(Note n) {
System.out.println("Guitar.play(" + n + ")");
}
}
class Electone extends Instrument {
public void play(Note n) {
System.out.println("Electone.play(" + n + ")");
}
}
class Piano extends Instrument {
public void play(Note n) {
System.out.println("Piano.play(" + n + ")");
}
}
class EPiano extends Piano {
}
Music2.java output
Guitar.play(C)
Piano.play(C)
Piano.play(C)
-----
Piano.play(C)
Guitar.play(C)
Electone.play(C)
Piano.play(C)
Piano.play(C)
Guitar.play(C)
Piano.play(C)
Electone.play(C)
Guitar.play(C)
Guitar.play(C)
Tag: Study Code Program Java
No comments:
Post a Comment