The actual question seems to be:
You have
interface Fruit
class Apple implements Fruit
class Banana implements Fruit
Then you have a method
public String checkFruitColor(List<Fruit> fruit)
And you have
List<Apple> apples = //something
List<Banana> bananas = //something
Now, you have made the (common) assumption and List<Apple>
is a subclass of List<Fruit>
because Apple
is a subclass of Fruit
.
But, that means we could do
List<Apple> apples = new ArrayList<Apple>();
List<Fruit> fruits = apples //all good as List<Apple> is a subclass of List<Fruit>
fruits.add(new Banana()); //we can add a Banana to a List<Fruit>
final Apple apple = apples.get(0); //a List<Apple> will always have apples.
OOPS!!
So, in fact, a List<Apple>
is not related to a List<Fruit>
- as far as the compiler is concerned they are completely different. Put in technical terms, List
is invariant in its type.
In order to make what you have work, you need to tell the compiler that you want a List
of some subtype of Fruit
but you don't care what.
public String checkFruitColor(List<? extends Fruit> fruit)
This will allow you to pass your List<Apple>
to checkFruitColor
and access the items as instances of Fruit
.
What you cannot do is add()
to the list as you do not know what the type of the List
is.