多态的使用
假设我们不知道有ArrayList这种类而想要自行编写维护的类以保存Dog对象,此时我们可以采用数组的方式来实现。在这个例子中我们只会写出add()方法。我们使用大小为5的简单Dog数组(Dog[])来保存新加入的Dog对象。当Dog对象超过5个时,你还是可以调用add()方法,但是什么事情也不会发生。如果没有越界,add()会把Dog装到可用的数组位置中,然后递增可用索引。
自己创建的Dog专用list
public class MyDogList { private Dog[] dogs = new Dog[5]; private int nextIndex = 0; public void add(Dog d) { if (nextIndex < dogs.length) { dogs[nextIndex] = d; System.out.println ("Dog added at "+ nextIndex); nextIndex++; } } }
如果也要写出Cat用的List,那要是写两个List不是太麻烦了吗?所以编写不同的AnimalList类让它处理Animal所有的子类。那你就可以直接调用这个List的add方法了。
abstract class Animal {
String name;
abstract public void eat();
}
class Dog extends Animal {
public void eat() {
System.out.println("狗吃骨头");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("猫吃鱼");
}
}
class MyAnimalList {
private Animal[] animals = new Animal[5];
private int nextIndex = 0;
public void add(Animal a) {
if (nextIndex < animals.length) {
animals[nextIndex] = a;
System.out.println("Animal addad at " + nextIndex);
nextIndex++;
}
}
}
public class AnimalTestDrive {
public static void main(String[] args) {
//在这里写代码
MyAnimalList list =new MyAnimalList();
Dog a=new Dog();
Cat c=new Cat();
list.add(a);
list.add(c);
}
}