在java编程方面,我仍然是个新手,所以虽然这看起来是一个非常简单的问题,但我就是不知道如何解决它。因此,最初我有这样的代码和这样的接口:
public interface Animal {
public String getSound();
public String getType();
}
定义动物的声音和类型的类,如:
public class Cow implements Animal{
String color;
public Cow(String c) {
color = c;
}
public String getSound() {
return "moo";
}
public String getType() {
return "cow";
}
public String getColor() {
return color;
}
}
然后我有一个类把所有的信息放在一起并打印出来:
public class OldMacDonaldApp {
public static void main(String[] args) {
Animal c;
c = new Cow("brown");
System.out.println("The " + ((Cow) c).getColor() + " " +c.getType() + " goes " + c.getSound());
c = new Chick(3);
System.out.println("The " + ((Chick) c).getAge() + " days old " + c.getType() + " goes " + c.getSound());
c = new Sheep("fluffy");
System.out.println("The " + ((Sheep) c).getTrait1() + " " + c.getType() + " goes " + c.getSound());
c = new Dog("loyal");
System.out.println("The " + ((Dog) c).getTrait2() + " " + c.getType() + " goes " + c.getSound());
}
}
但是,我必须创建这个新的农场类,它使用数组来测试所有的动物:
import java.util.*;
public class Farm{
private ArrayList <Animal> myFarm;
public Farm() {
myFarm = new ArrayList <Animal>();
}
public void addAnimal(Animal animal) {
myFarm.add(animal);
}
public void animalSounds() {
Animal a;
for (int i=0; i < myFarm.size(); i++) {
a = myFarm.get(i);
System.out.println(a.getType() + " goes " + a.getSound());
}
}
}
现在我必须修改OldMacDonaldApp类代码,这样我就可以创建一个对象Farm并使用addAnimal和animalSounds方法。我知道这可能真的很简单,我可能错过了一些非常明显的东西,但我不知道该怎么做。如能提供帮助,我将不胜感激。
现在Farm
类完成了所有的工作,所以我们可以简单地使用addAnimal(...)
方法创建和添加动物,然后使用animalSounds()
方法将它们全部打印出来:
public class OldMacDonaldApp {
public static void main(String[] args) {
//Create the farm object the same way as creating a new animal
Farm myFarm = new Farm();
//Add animals to the farm using the addAnimal method of the Farm
myfarm.addAnimal(new Cow("brown"));
myfarm.addAnimal(new Chick(3));
myfarm.addAnimal(new Sheep("fluffy"));
myfarm.addAnimal(new Dog("loyal"));
//Now print the sounds with the animalSounds method in the Farm class
myfarm.animalSounds();
}
}