所以我有一个界面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()
对象上调用pet
方法。
您可以引用以下代码并遵循内联注释:
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<>();
或Puppies spot = new Puppies();
。最佳实践是您需要将对象分配给接口(interface)类型
List<Pet> pets = new ArrayList<Pet>();
或Pet spot = new Puppies();
(接口(interface)类型称为代码)