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