/**
* 抽象的动物父类
* @author win8
*
*/
public abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
* 叫方法
*/
public abstract void shout();
}
package page2_197;
/**
* 猫类
* @author win8
*
*/
public class Cat extends Animal implements Terrestrial{
private int legNum;
public Cat(String name,int legNum) {
super(name);
this.legNum=legNum;
}
public int getLegNum() {
return legNum;
}
public void shout() {
System.out.println("喵喵喵....");
}
}
package page2_197;
/**
* 鸭子类
* @author win8
*
*/
public class Duck extends Animal implements Terrestrial{
private int legNum;
public Duck(String name,int legNum) {
super(name);
this.legNum=legNum;
}
public int getLegNum() {
return legNum;
}
public void shout() {
System.out.println("嘎嘎嘎....");
}
}
package page2_197;
/**
* 海豚类
* @author win8
*
*/
public class Dolphin extends Animal {
public Dolphin(String name) {
super(name);
}
public void shout() {
System.out.println("海豚音....");
}
}
package page2_197;
/**
* 陆地生物
* @author win8
* 获得腿数
*/
public interface Terrestrial {
public int getLegNum();
}
package page2_197;
import java.util.Scanner;
/**
* 测试类
* @author win8
*
*/
public class AnimalMgr {
static Animal[] animals = new Animal[3];
static Scanner input = new Scanner(System.in);
static int num;
public static void showAnimal() { //显示动物信息
System.out.println("动物名字\t\t腿的条数\t\t动物叫");
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 + "\t\t" + legNum + "\t\t");
animals[i].shout();
} else { //海豚除外
String name = animals[i].getName();
System.out.print(name + "\t\t" + 0 + "\t\t");
animals[i].shout();
}
}
System.out.println("是否要继续修改数据:按0进行修改操作,其它任意数字键退出");
}
public static void modifyAnimal() throws Exception { //修改动物信息
String[] names = new String[3];
int[] number = new int[3];
System.out.println("请输入猫的名称");
names[0] = input.next();
System.out.println("请输入猫腿的条数");
number[0] = input.nextInt();
if (number[0] != 4) {
throw new Exception("猫是有4条腿"); //腿的条数错误,抛出异常
}
System.out.println("请输入鸭子的名称");
names[1] = input.next();
System.out.println("请输入鸭子腿的条数");
number[1] = input.nextInt();
if (number[1] != 2) {
throw new Exception("鸭子是有两条腿"); //腿的条数错误,抛出异常
}
System.out.println("请输入海豚的名称");
names[2] = input.next();
animals[0] = new Cat(names[0], number[0]); //跟新信息
animals[1] = new Duck(names[1], number[1]);
animals[2] = new Dolphin(names[2]);
}
public static void main(String[] args) {
animals[0] = new Cat("加菲猫", 4); //添加原始数据
animals[1] = new Duck("唐老鸭", 2);
animals[2] = new Dolphin("海豚奇奇");
showAnimal(); //显示动物信息
num = input.nextInt();
while (num == 0) { //当输入0时循坏
try {
modifyAnimal(); //提示修改信息
} catch (Exception e) {
e.printStackTrace(); //显示异常信息
} finally {
showAnimal(); //重复操作
num = input.nextInt();
}
}
System.out.println("谢谢使用!");
}
}