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);
// }
}
}