package HomeWork;
import java.util.Scanner;
/**
* 2. 编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。可以弹奏的乐器包括二胡、钢琴和琵琶。
实现思路及关键代码:
1) 定义乐器类Instrument,包括方法makeSound();
2) 定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin;
3) 定义乐手类Musician,可以弹奏各种乐器play(Instrument i);
4) 定义测试类,给乐手不同的乐器让他弹奏。
* @author lenovo
*
*/
public class HomeWork02 {
public static void main(String[] args) {
boolean flag = true;
Erhu e = new Erhu();
Pinao p = new Pinao();
Violin v = new Violin();
Musician m = new Musician();
Scanner scanner = new Scanner(System.in);
while(flag){
System.out.println("########################");
System.out.println("请按对应的数字选择演奏的乐器类型:");
System.out.println("0--二胡");
System.out.println("1--钢琴");
System.out.println("2--小提琴");
int type = scanner.nextInt();
if(type==0){
m.play(e);
}
if(type==1){
m.play(p);
}
if(type==2){
m.play(v);
}
System.out.println("可以按任意数字继续!");
int s = scanner.nextInt();
if(s == 9){
}
}
}
}
//乐器类
abstract class Instrument {
String name;
String sound;
abstract String makesound();
}
//二胡乐器子类
class Erhu extends Instrument {
Erhu(){
this.name = "二胡";
this.sound = "正在演奏二胡声!";
}
String makesound(){
return this.sound;
}
}
//钢琴乐器子类
class Pinao extends Instrument {
Pinao(){
this.name = "钢琴";
this.sound = "正在演奏钢琴声!";
}
String makesound(){
return this.sound;
}
}
//小提琴乐器子类
class Violin extends Instrument {
Violin(){
this.name = "小提琴";
this.sound = "正在演奏小提琴声!";
}
String makesound(){
return this.sound;
}
}
//乐手类
class Musician {
void play(Instrument i){
System.out.println(i.makesound());
}
}