2、 请使用接口编码实现如下需求:乐器(Instrument,定义为接口)分为:钢琴(Piano,具体实现类)、小提琴(Violin,具体实现类),各种乐器的弹奏( play )方法各不相同。编写一个测试类InstrumentTest,要求:编写方法testPlay,对各种乐器进行弹奏测试。要依据乐器的不同,进行相应的弹奏。在main方法中创建不同的乐器对象,通过testPlay的弹奏测试方法进行测试。
时间: 2023-06-16 21:03:41 浏览: 57
接口 Instrument 的代码如下:
```
public interface Instrument {
void play();
}
```
钢琴 Piano 的代码如下:
```
public class Piano implements Instrument {
public void play() {
System.out.println("钢琴演奏中...");
}
}
```
小提琴 Violin 的代码如下:
```
public class Violin implements Instrument {
public void play() {
System.out.println("小提琴演奏中...");
}
}
```
测试类 InstrumentTest 的代码如下:
```
public class InstrumentTest {
public static void main(String[] args) {
Instrument piano = new Piano();
Instrument violin = new Violin();
testPlay(piano);
testPlay(violin);
}
public static void testPlay(Instrument instrument) {
instrument.play();
}
}
```
在 main 方法中,我们创建了一个钢琴对象和一个小提琴对象,并分别调用了 testPlay 方法来测试它们的演奏效果。testPlay 方法接收一个 Instrument 类型的参数,因为钢琴和小提琴都实现了 Instrument 接口,所以它们都可以作为参数传入 testPlay 方法中。在 testPlay 方法中,我们调用了各自的 play 方法,来展示不同乐器的演奏效果。