综合练习

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

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	海豚音...
*******************/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值