Java 实现飞行接口:鸟类和昆虫类的示例
interface Flyable {\n void fly();\n}\n\nclass Bird implements Flyable {\n private int legs;\n\n public Bird(int legs) {\n this.legs = legs;\n }\n\n public void layEggs() {\n System.out.println("我可以生蛋");\n }\n\n public void fly() {\n System.out.println("我可以飞");\n }\n\n public int getLegs() {\n return legs;\n }\n}\n\nclass Insect implements Flyable {\n private int legs;\n\n public Insect(int legs) {\n this.legs = legs;\n }\n\n public void layEggs() {\n System.out.println("我可以产卵");\n }\n\n public void fly() {\n System.out.println("我可以飞");\n }\n\n public int getLegs() {\n return legs;\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n Bird pigeon = new Bird(2);\n pigeon.layEggs();\n pigeon.fly();\n System.out.println("我是鸽子,我有" + pigeon.getLegs() + "只腿,我可以生蛋,我可以飞");\n\n Bird wildGoose = new Bird(2);\n wildGoose.layEggs();\n wildGoose.fly();\n System.out.println("我是大雁,我有" + wildGoose.getLegs() + "只腿,我可以生蛋,我可以飞");\n\n Insect ant = new Insect(6);\n ant.layEggs();\n ant.fly();\n System.out.println("我是蚂蚁,我有" + ant.getLegs() + "只腿,我可以产卵,我可以飞");\n\n Insect bee = new Insect(6);\n bee.layEggs();\n bee.fly();\n System.out.println("我是蜜蜂,我有" + bee.getLegs() + "只腿,我可以产卵,我可以飞");\n }\n}
原文地址: https://www.cveoy.top/t/topic/pUnk 著作权归作者所有。请勿转载和采集!