我有一些实现通用接口的对象。假设我有Apple
和一些其他Fruits
实现HasSeed
并返回它们的种子数量。如何传递一个方法列表<Interface>而不是列表<Class>?
然后我有一个服务方法,在这里称之为FruitProcessor
,类别为addAll(List<HasSeed>)
。我想我可以通过一个实现HasSeed
接口的对象列表,就像苹果列表一样。
但我不能和编译器抱怨说它不适用于参数。 还有一件事:我不能将List<Apple>
更改为List<HasSeed>
。但是我需要一个可以接受任何对象列表的FruitProcessor中的方法,然后不管它是什么对象,都调用getSeeds()
。
我怎么能适应以下?
class Fruit {};
class Apple extends Fruit implements HasSeed {
@Override
int getSeeds() {
return 5; //just an example
}
}
class FruitProcessor {
static void addAll(List<HasSeed> list) {
for (HasSeed seed : list) {
Sysout("the fruit added contained seeds: " + list.getSeeds());
}
}
}
class FruitStore {
List<Apple> apples;
FruitProcessor.addAll(apples); //The method addAll(List<HasSeed>) in the type FruitProcessor is not applicable for the arguments (List<Apple>)
}