java – 如何为ArrayList中的所有对象调用方法?
所以我有一个界面Pet如下所示:
public interface Pet{ void Eat(); } 这是由以下实现的: public class Puppies implements Pet { @Override public void Eat() { // Something gets eaten here,presumably } } 和 public class Kittens implements Pet { @Override public void Eat() { // Everybody knows Kittens eats something different } } 希望我接下来要做的是创建一个新宠物的ArrayList: public class PetList{ public PetList(){ ArrayList pets = new ArrayList<Pet>(); Puppies spot = new Puppies(); Puppies rex = new Puppies(); Kittens meowth = new Kittens(); pets.add(spot); pets.add(rex); pets.add(meowth); } public static void main(String[] args){ // No idea how to handle this bit } 接下来我要做的就是告诉我所有的宠物都吃.我该怎么做? 解决方法
当前代码的主要问题是ArrayList(pets)是PetList构造函数的本地问题,这意味着您无法访问类PetList的构造函数外部.
因此,首先,将ArrayList作为PetList类的实例变量,以便即使在构造函数之外也可以通过对象访问它. 然后,您可以提供一个eatAll()方法,该方法迭代ArrayList< Pet>并在所有宠物对象上调用eat()方法. 您可以参考以下代码并遵循内联注释: public class PetList{ private List<Pet> pets;//now this is an instance variable public PetList(){ this.pets = new ArrayList<Pet>();//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();(称为接口类型的代码) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |