编程题
//Animal抽象类
public abstract class Animal {
private String name;
public Animal() {}
public Animal(String name) {
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//play方法 模拟小动物做游戏
public abstract void play(String name);
}
//Dog子类继承自Animal
public class Dog extends Animal{
public Dog(String name) {
this.setName(name);
}
public Dog(){}
@Override
public void play(String name) {
System.out.println(name + "在做游戏!");
}
}
//Cat子类继承自Animal
public class Cat extends Animal {
public Cat(String name) {
this.setName(name);
}
public Cat(){}
@Override
public void play(String name) {
System.out.println(name + "在做游戏!");
}
}
//AnimalPlay类
import java.util.List;
public class AnimalPlay {
public void playGames(List<? extends Animal> animal) {
for(Animal a : animal) {
a.play(a.getName());
}
}
}
//AnimalTest类
import java.util.ArrayList;
import java.util.List;
public class AnimalTest {
public static void main(String[] args) {
//创建DogList并添加dog对象
List<Dog> dog = new ArrayList<>();
dog.add(new Dog("小狗巴迪"));
dog.add(new Dog("小狗豆豆"));
//创建CatList并添加cat对象
List<Cat> cat = new ArrayList<>();
cat.add(new Cat("小猫花花"));
cat.add(new Cat("小猫凡凡"));
//创建AnimalPlay对象,并调用playGames方法 分别传入dog、cat List
AnimalPlay a = new AnimalPlay();
a.playGames(dog);
a.playGames(cat);
}
}