面向对象_练习03

``
 白色4条腿的北极熊(Bear)会吃(吃蜂蜜)和抓鱼(catchFish)
 黑色4条腿的大熊猫(Panda)会吃(吃竹子)和爬树(climbTree)
 要求: 把北极熊和大熊猫的共性提取动物类(Animal)中,使用抽象类

public class test {
	public static void main(String[] args) {
		//创建对象
		Bear a1=new Bear("白色",4);
    //抽象类 父类需要用子类实例化来调用父类中的方法或者重写的方法,
    //如果子类有自己的特有的方法则必须创建子类对象
		Panda a2=new Panda("黑色",4);
		System.out.println(a1.getColor()+a1.getNumOfLegs());
		a1.eat();
		a1.catchFish();
		System.out.println(a2.getColor()+a2.getNumOfLegs());
		a2.eat();
		a2.climbTree();
	}
}
public abstract class Animal {
	private String color;
	private int numOfLegs;
	public Animal() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Animal(String color, int numOfLegs) {
		this.color = color;
		this.numOfLegs = numOfLegs;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getNumOfLegs() {
		return numOfLegs;
	}
	public void setNumOfLegs(int numOfLegs) {
		this.numOfLegs = numOfLegs;
	}
	//定义吃东西的抽象方法
    public abstract void eat();
}
public class Bear extends Animal {
	
	
	public Bear() {
		super();
		// TODO Auto-generated constructor stub
	}

	
	public Bear(String color, int numOfLegs) {
		super(color, numOfLegs);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void eat() {
		
		System.out.println("吃蜂蜜");
	}
	public void catchFish() {
		System.out.println("抓鱼");
	}
}
public class Panda extends Animal {

	public Panda() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Panda(String color, int numOfLegs) {
		super(color, numOfLegs);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void eat() {
		// TODO Auto-generated method stub
		System.out.println("吃竹子");
		
	}
	public void climbTree() {
		System.out.println("爬树");
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值