动物乐园
任务描述:
以面向对象思想设计动物乐园系统
动物乐园包括的成员:猫、鸭子,海豚,……
属性:名称、腿
方法:叫
设计类图
使用多态、接口优化设计
编码实现
分别创建Cat、Duck、Dolphin对象并放到一个数组中,对数组进行遍历输出各种动物如何叫,各种动物腿的条数。instanceof判断动物种类 。
package com.Summer_0428.cn; abstract class Animal1{ private String name; public Animal1(String name) { this.name = name; } public String getName() { return name; } public abstract void show();//定义一个抽象方法 } interface Terrestrial{ public int getLegNum(); } class Cat1 extends Animal1 implements Terrestrial{ private int legNum; public Cat1(String name,int legNum) { super(name); this.legNum = legNum; } @Override public int getLegNum() { return legNum; } @Override public void show() { System.out.println("喵喵喵"); } } class Duck extends Animal1 implements Terrestrial{ private int legNum; public Duck(String name,int legNum) { super(name); this.legNum = legNum; } @Override public int getLegNum() { return legNum; } @Override public void show() { System.out.println("嘎嘎嘎"); } } class Dolphin extends Animal1 { public Dolphin(String name) { super(name); } @Override public void show() { System.out.println("海豚音"); } } public class Zoo { public static void main(String[] args) { Animal1 animals[] = new Animal1[3]; animals[0] = new Cat1("加菲猫", 4); animals[1] = new Duck("唐小鸭", 2); animals[2] = new Dolphin("海豚奇奇"); System.out.println("动物名字 腿的条数 动物叫"); for (int i = 0; i < animals.length; i++){ if (animals[i] instanceof Terrestrial) { String name = animals[i].getName(); int legNum = ((Terrestrial) animals[i]).getLegNum(); System.out.print(name + " " + legNum + " "); animals[i].show(); } else { String name = animals[i].getName(); System.out.print(name + " " + 0 + " "); animals[i].show(); } } } }