综合练习

本程序综合练习继承、抽象类、抽象方法、多态、接口的使用,这之后就开始学习集合、异常。

package com.test.code;
	/*
	 * Terrestrial 接口	带腿的陆生动物
	 */
interface Terrestrial{
	public int getLegNum();
}
	/*
	 * 动物类-抽象
	 */
abstract class  Animal{
	String name;
	/*
	 * 构造方法
	 */
	public Animal(String name){
		this.name = name;
	}
	/*
	 * 动物叫声明为抽象方法
	 */
	public abstract void shout();
	
}
	/*
	 * 猫类
	 */
class Cat extends Animal implements Terrestrial{
	int legNum = 0;
	/*
	 * 构造方法
	 */
	public Cat(String name, int legNum) {
		super(name);
		this.legNum = legNum;
	}
	//得到腿数
	public int getLegNum(){
		return legNum;
	}
	/*
	 * 重写父类Animal 的 shout()方法;
	 */
	public void shout(){
		System.out.println("喵喵喵...");
	}
}
	/*
	 * 鸭类
	 */
class Duck extends Animal implements Terrestrial{
	int legNum = 0;
	/*
	 * 构造方法
	 */
	public Duck(String name, int legNum){
		super(name);
		this.legNum = legNum;
	}
	//得到腿数
	public int getLegNum(){
		return legNum;
	}
	@Override
	public void shout() {
		System.out.println("嘎嘎嘎...");
	}
}
	/*
	 * 海豚类
	 */
class Dolphin extends Animal{
	public Dolphin(String name){
		super(name);
	}
	public void shout(){
		System.out.println("海豚音...");
	}
}
public class Test2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * 创建 Animal []对象数组
		 */
		Animal animals[] = new Animal[3];
		animals[0] = new Cat("白老猫", 4);
		animals[1] = new Duck("黄小鸭", 2);
		animals[2] = new Dolphin("海小豚");
		System.out.println("动物名\t"+"腿条数"+"\t动物叫");
		System.out.println("****************************");
		for(int i=0; i<animals.length; i++){
			int legNum = 0;
			if(animals[i] instanceof Terrestrial){
				Terrestrial t = (Terrestrial) animals[i];
				legNum = t.getLegNum();
			}
			System.out.print(animals[i].name+"\t"+legNum+"\t");
			animals[i].shout();
			/*	头一回写了下面的语句,原来不可以这样...
			 * System.out.print(animals[i].shout()) error;	
			 * 提示错误:类型 PrintStream 中的方法 print(boolean)对于参数(void)不适用
			 * */
		}
	}

}
/*******************
动物名	腿条数	动物叫
****************************
白老猫	4	喵喵喵...
黄小鸭	2	嘎嘎嘎...
海小豚	0	海豚音...
*******************/




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章