如何传递List <Interface>而不是List <Class>的方法?

mem*_*und 3 java oop collections interface

我有一些实现通用接口的对象.假设我Apple和其他Fruits一些人实施HasSeed并返回他们的种子数量.

然后我有一个服务方法,FruitProcessor在这里调用它,与一个addAll(List<HasSeed>)类.我以为我可以传入一个实现HasSeed界面的对象列表,就像苹果列表一样.

但我不能和编译器抱怨它不适用于参数.还有一件事:我无法改变List<Apple>为a 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>)
}
Run Code Online (Sandbox Code Playgroud)

pho*_*360 11

你必须使用 List<? extends HasSeed>

背后的原因是List<Apple>不延伸List<HasSeed>.当您List<? extends HasSeed>在签名中写入时,这意味着您接受实现该HasSeed接口的任何元素列表.这就是为什么你可以通过List<Apple>一个List<? extends HasSeed>