T2.编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。可以弹奏的乐器包括二胡、钢琴和琵琶。要求:
(1)定义乐器类Instrument,包括方法makeSound()
(2)定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin
(3)定义乐手类Musician,可以弹奏各种乐器play(Instrument i)
(4)定义测试类,给乐手不同的乐器让他弹奏。
(1)定义乐器类Instrument,包括方法makeSound()
public class Instrument {public void makeSound() {System.out.println("发出声音");}
}
(2)定义乐器类的子类:二胡Erhu、钢琴Piano和小提琴Violin
public class Erhu extends Instrument{@Overridepublic void makeSound() {System.out.println("二胡发出嘹亮的声音");}
}
public class Piano extends Instrument{@Overridepublic void makeSound() {System.out.println("钢琴发出悦耳的声音");}
}
public class Violin extends Instrument{@Overridepublic void makeSound() {System.out.println("小提琴发出柔和的声音");}
}
(3)定义乐手类Musician,可以弹奏各种乐器play(Instrument i)
public class Musician {public void play(Instrument instru){instru.makeSound();}
}
4)定义测试类,给乐手不同的乐器让他弹奏
public class test {public static void main(String[] args) {Musician m=new Musician();Instrument erhu=new Erhu();Instrument piano=new Piano();Instrument violin=new Violin();m.play(erhu);m.play(piano);m.play(violin);}
}