请编码实现如下需求: 乐器(Instrument)分为:钢琴(Piano)、小提琴(Violin) 各种乐器的弹奏( play )方法各不相同。 编写方法testPlay,对各种乐器进行弹奏测试。要依据乐器的不同,进行相应的弹奏。
时间: 2024-05-08 12:17:10 浏览: 30
下面是一个Java的实现示例:
```java
//乐器抽象类
abstract class Instrument {
public abstract void play();
}
//钢琴类
class Piano extends Instrument {
public void play() {
System.out.println("钢琴演奏中...");
}
}
//小提琴类
class Violin extends Instrument {
public void play() {
System.out.println("小提琴演奏中...");
}
}
public class Test {
public static void main(String[] args) {
Instrument[] instruments = {new Piano(), new Violin()};
for (Instrument instrument : instruments) {
testPlay(instrument);
}
}
public static void testPlay(Instrument instrument) {
instrument.play();
}
}
```
在这个例子中,我们定义了一个抽象类Instrument,其中定义了一个抽象方法play(),表示乐器的弹奏方法。然后我们分别实现了钢琴和小提琴类,重写了play()方法。最后在main()方法中,我们创建了一个乐器数组,并遍历数组调用testPlay()方法进行测试。在testPlay()方法中,我们根据传入的乐器对象调用其play()方法,实现了多态的应用。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)