【发布时间】:2013-03-18 09:27:00
【问题描述】:
我有一些实现通用接口的对象。假设我有 Apple 和其他一些 Fruits 实现 HasSeed 并返回它们的种子数量。
然后我有一个服务方法,在这里称之为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>)
}
【问题讨论】:
标签: java oop collections interface