Week2-12 abstractExample

package abstractExample;

import java.awt.Color;

public abstract class Creature
{
	protected String name, tailType;
	protected Color color;
	protected int speed;

	public abstract int run(int duration, boolean zigzag);

	public void swim(int duration)
	{
	};

}
package abstractExample;

public class Rabbit extends Creature
{
	public int run(int duration, boolean zigzag)
	{
		System.out.println("i can run like a rabbit");
		if (zigzag)
		{
			return (int) (duration * speed * 0.25);
		}
		return duration * speed;
	}

}
package abstractExample;

public class Turtle extends Creature
{
	public int run(int duration, boolean zigzag)
	{
		System.out.println("i can run like a turtle");
		if (zigzag)
		{
			return (int) (duration * speed * 0.25);
		}
		return duration * speed;
	}

}

用数组实现

package abstractExample;

public class CreatureArray
{
	// 创建creature类型的ArrayList
	private Creature[] creatureArray = new Creature[5];
	private int nextIndex = 0;

	// 向数组赋值
	public void addToList(Creature r)
	{
		if (nextIndex < 5)
		{
			creatureArray[nextIndex] = r;
			System.out.println("creature added at " + nextIndex + " " + r);
			nextIndex++;
		}

	}

}
package abstractExample;

public class CreatureTest
{
	public static void main(String[] args)
	{
		CreatureArray array = new CreatureArray();
		Turtle t1 = new Turtle();
		Rabbit r1 = new Rabbit();
		array.addToList(r1);
		array.addToList(t1);
		array.addToList(new Rabbit());

	}

}

用ArrayList实现:

package abstractExample;

import java.util.ArrayList;

public class CreatureList
{
	public static void main(String[] args)
	{
		ArrayList<Creature> cList = new ArrayList<>();
		Turtle t1 = new Turtle();
		Rabbit r1 = new Rabbit();

		cList.add(t1);
		cList.add(r1);
		cList.add(new Rabbit());
		for (Creature c : cList)
		{
			c.run(5, true);
		}
//		for(int i = 0;i<cList.size();i++)
//		{
//			cList.get(i).run(5, true);
//		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值