编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。
可以弹奏的乐器包括二胡、钢琴和琵琶。
实现思路及关键代码:
①定义乐器类Instrument,包括方法makeSound()
②定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin
③定义乐手类Musician,可以弹奏各种乐器makeSound(Instrument instrument)
④定义测试类,给乐手不同的乐器让他弹奏
package jsu.std.ddd;
public class Instrument {
public void makeSound(){
System.out.println("乐器发出声音!");
}
}
package jsu.std.ddd;
public class Erhu extends Instrument{
public void makeSound(){
System.out.println("二胡发出声音!");
}
}
package jsu.std.ddd;
public class Piano extends Instrument{
public void makeSound(){
System.out.println("钢琴发出声音!");
}
}
package jsu.std.ddd;
public class Violin extends Instrument{
@Override
public void makeSound() {
System.out.println("小提琴发出声音!");
}
}
package jsu.std.ddd;
public class Musician {
public void using(Instrument instrument){
instrument.makeSound();
}
}
package jsu.std.ddd;
public class TestInstrument {
public static void main(String[]args){
Musician musician = new Musician();
Instrument erhu = new Erhu();
Instrument piano = new Piano();
Instrument violin = new Violin();
musician.using(erhu);
musician.using(piano);
musician.using(violin);
}
}