码迷,mamicode.com
首页 > 编程语言 > 详细

Java 动物声音“模拟器”(用接口实现)

时间:2020-06-21 11:50:44      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:interface   oid   实现   system   print   simulator   模拟   rac   sys   

(1)编写接口Animal (Animal.java)

public interface Animal{
    public abstract void cry();
    public abstract String getAnimalName();
}

(2)编写模拟类Simulator (Simulator.java)

public class Simulator {
    public void playSound(Animal animal) {
        System.out.print("正在播放模拟" + animal.getAnimalName() +"的声音:");
        animal.cry();
    }
}

(3)编写Dog类和Cat类 (Dog.java、Cat.java)
Dog类:

public class Dog implements Animal{
    public void cry(){
        System.out.println("汪汪汪");
    }
    public String getAnimalName(){
        return "狗";
    }
}

Cat类:

public class Cat implements Animal{
    public void cry(){
        System.out.println("喵喵喵");
    }
    public String getAnimalName(){
        return "猫";
    }
}

(4)编写主类Application (Application.java)

public class Application{
    public static void main(String[] args) {
        Simulator simulator = new Simulator();
        simulator.playSound(new Dog());
        simulator.playSound(new Cat());
    }
}

Java 动物声音“模拟器”(用接口实现)

标签:interface   oid   实现   system   print   simulator   模拟   rac   sys   

原文地址:https://www.cnblogs.com/chenrengu/p/13171774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!