我有一些实现了共同接口的对象。比如说,我有
然后,我有一个服务方法,称之为
但是我不能这么做,编译器会提示该参数不适用。 还有一件事:我不能将
我该如何调整以下代码?
Apple
和其他一些实现HasSeed
接口并返回其籽数的Fruits
。然后,我有一个服务方法,称之为
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>)
}
private <T extends HasSeed> List<T> doSomething(List<T> arg)
为什么不能正常工作? - user3529850