编程题2:
/*请使川接口编码实现如下要求:乐器(Instrument)分为:钢琴(Piano)、小提琴(Violin).各种乐器的弹奏( play )方法各不相同。
编写一个测试类InstrumentTest,要求;
编写方法testPlay,对各种乐器进行弹奏测试。要依据乐器的不同,进行相应的弹奏。在main方法中创建不同的乐器对象,通过testPlay的弹奏测试方法进行测试。
*/
package com.zgc.test1;
import com.zgc.test.USB;
public class InstrumentTest {
public static void main(String[] args) {
Piano p = new Piano();
testPlay(p);
Violin v = new Violin();
testPlay(v);
}
public static void testPlay(Instrument i){
i.play();
}
}
interface Instrument{
void play();
}
class Piano implements Instrument{
@Override
public void play() {
System.out.println("弹奏钢琴");
}
}
class Violin implements Instrument{
@Override
public void play() {
System.out.println("拉小提琴");
}
}
运行结果:
弹奏钢琴
拉小提琴
进程已结束,退出代码0