1.Animal类
package com.yfs.javase;
public class Animal {
public void cry() {
System.out.println("动物叫...");
}
}
2.Dog/Cat/Bird类
package com.yfs.javase;
public class Dog extends Animal {
public void cry() {
System.out.println("汪 汪...");
}
}
class Cat extends Animal {
public void cry () {
System.out.println("喵 喵...");
}
}
class Bird extends Animal {
public void cry () {
System.out.println("嘎 嘎...");
}
}
3.Box类,(集合)
package com.yfs.javase;
public class Box {
// 动物房在哪里 10個動物
// private Dog[] dogs = new Dog[10];
// private Cat[] cats = new Cat[10];
// private Bird[] birds = new Bird[10];
//声明父类数组
private Animal[] animals = new Animal[10];
private int index = 0;
// 装动物
public void addAnimal(Animal pet) {
if (index >= 10) {
System.out.println("箱子已满");
return;
}
animals[index] = pet;
index++;
//System.out.println(pet);
}
//
// public void addAnimal(Cat cat) {
// if (index >= 10) {
// System.out.println("箱子已满");
// return;
// }
// cats[index] = cat;
// index++;
// }
// 踢箱子
public void kid() {
for (int i = 0; i < animals.length; i++) {
animals[i].cry();//执行的是子类的方法 多态 覆盖的方法
}
}
}
4.Box测试
package com.yfs.javase;
import java.util.Random;
public class BoxTest {
public static void main(String[] args) {
Box box = new Box();
// box.addAnimal(new Dog());
// box.addAnimal(new Bird());
// box.addAnimal(new Cat());
Random ran = new Random();
for (int i = 0; i < 15; i++) {
int r = ran.nextInt(101);// 100 65 35
if(r > 65) {
box.addAnimal(new Dog());
} else if( r > 35) {
box.addAnimal(new Cat());
} else {
box.addAnimal(new Bird());
}
}
box.kid();
}
}