Java基于接口实现模拟动物声音代码实例
(1)编写接口Animal(Animal.java)
publicinterfaceAnimal{ publicabstractvoidcry(); publicabstractStringgetAnimalName(); }
(2)编写模拟类Simulator(Simulator.java)
publicclassSimulator{ publicvoidplaySound(Animalanimal){ System.out.print("正在播放模拟"+animal.getAnimalName()+"的声音:"); animal.cry(); } }
(3)编写Dog类和Cat类(Dog.java、Cat.java)
Dog类:
publicclassDogimplementsAnimal{ publicvoidcry(){ System.out.println("汪汪汪"); } publicStringgetAnimalName(){ return"狗"; } }
Cat类:
publicclassCatimplementsAnimal{ publicvoidcry(){ System.out.println("喵喵喵"); } publicStringgetAnimalName(){ return"猫"; } }
(4)编写主类Application(Application.java)
publicclassApplication{ publicstaticvoidmain(String[]args){ Simulatorsimulator=newSimulator(); simulator.playSound(newDog()); simulator.playSound(newCat()); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。