Trying to understand Generics with Consumer.
class Fruit{}
class Apple extends Fruit{}
class Orange extends Fruit{}
class Util{
private Collection<Apple> appleList = new ArrayList<>();
public Util(){
acceptFruit(ap -> appleList.add(ap);
}
public <T extends Fruit> void acceptFruit(Consumer<T> fruitConsumer){
//FruitService.getAllFruits();
//some validations and get fruit object
fruitConsumer.accept(fruit);
}
}
//Some other class calling Util.acceptFruit(orange -> oranges.add(orange);
I get compilation errors on:
acceptFruit(ap -> appleList.add(ap);
add (Apple) in Collection can not be applied to (Fruit)
and on:
fruit.accept(fruit);
accept (T) in Consumer cannot be applied to (Apple)
Since Apple
is extending Fruit
, I don't understand why I am getting this error? Any idea on what I am missing in Generics/Consumer concepts?