java Some usage questions about "? super Fruit"

ciampion :

I got a problem ,eg :

Fruit Class

public class Fruit extends Food {

    public static void main(String[] args) {
        Plate<? super Fruit> plate = new Plate<>(new Food());
        plate.setItem(new Apple());
        plate.setItem(new Food());
    }


    static class Apple extends Fruit {

    }
}

Food Class

public class Food {
}

Plate Class'

public class Plate<T> {

    private T item;

    public Plate(T t) {
        item = t;
    }

    public T getItem() {
        return item;
    }

    public void setItem(T item) {
        this.item = item;
    }
}

I don't understand why

Plate<? super Fruit> plate = new Plate<>(new Food())

not error

but

plate.setItem(new Food()) 

is error

What is the difference between these two methods?

-that all, thanks!

Sweeper :

There are two things happening on this line:

Plate<? super Fruit> plate = new Plate<>(new Food());

new Plate<>(new Foo()) creates a new instance of Plate. The generic parameter here is inferred to be Food, so the right hand side creates a Plate<Food> object.

The second thing is that this object is assigned to plate. plate can be a Plate<T> as long as T is Fruit or a super class of Fruit. Is Food a superclass of Fruit? Yes, so the right hand side can be assigned to plate.

On this line however:

plate.setItem(new Food()) 

You are setting a plate's item. That plate could be a plate of anything, as long as it is Fruit or a superclass of Fruit. This means that passing a Food object wouldn't work. Why? Well, what if plate is actually a Plate<Fruit>? It could be, couldn't it? The compiler doesn't know.

So the only thing you can pass to plate.setItem are Fruit and subclasses of Fruit.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=123606&siteId=1