1 abstract class Animala{ 2 String name; 3 abstract public void eat(); 4 5 } 6 class Dog extends Animala{ 7 public void eat(){ 8 System.out.println("狗吃骨头"); 9 } 10 } 11 class Cat extends Animala{ 12 public void eat(){ 13 System.out.println("猫吃鱼"); 14 } 15 } 16 class MyAnimalList{ 17 private Animala[] animals = new Animala[5]; //初始化数组,即这个数组里可以放5个Animala类型的类的对象 18 private int nextIndex = 0; //下标 19 20 public void add(Animala a){ 21 if(nextIndex < animals.length){ 22 animals[nextIndex] = a; 23 System.out.println("Animal add at "+ nextIndex ); 24 nextIndex++; 25 } 26 } 27 } 28 public class ThreeDuo { 29 public static void main(String[] args){ 30 MyAnimalList list = new MyAnimalList(); //定义集合的对象 31 Cat a = new Cat(); 32 Dog c = new Dog(); 33 list.add(a); 34 list.add(c); 35 } 36 }
时间: 2024-12-28 00:38:56