当前代码的主要问题是ArrayList(pets)是PetList构造函数的本地问题,这意味着您无法访问类PetList的构造函数外部.
因此,首先,将ArrayList作为PetList类的实例变量,以便即使在构造函数之外也可以通过对象访问它.
然后,您可以提供一个eatAll()方法,该方法迭代ArrayList< Pet>并在所有宠物对象上调用eat()方法.
您可以参考以下代码并遵循内联注释:
public class PetList{
private List pets;//now this is an instance variable
public PetList(){
this.pets = new ArrayList();//this list is not local now
Puppies spot = new Puppies();
Puppies rex = new Puppies();
Kittens meowth = new Kittens();
pets.add(spot);
pets.add(rex);
pets.add(meowth);
}
public void eatAll() { //method to invoke eat() on list of pets
for(Pet pet : this.pets) { //iterate the pets list
pet.eat();//call eat() on each pet object
}
}
public static void main(String[] args){
PetList petList = new PetList();
petList.eatAll();//invoke the eatAll() method
}
}
作为旁注,我强烈建议你遵循Java命名标准(Eat()应该是eat(),即方法名称应该以小写开头)并考虑将PetList类重命名为PetsTesting(或其他东西),这样它会更多直观的开发人员.
最后,但重要的是不要将对象直接分配给具体的类类型,如ArrayList< Pet> pets = new ArrayList<>();或小狗斑点=新小狗();.
最佳实践是您需要将对象分配给接口类型List< Pet> pets = new ArrayList< Pet>();或Pet spot = new Puppies();(称为接口类型的代码)