Why a generic method of an interface can be implemented as non-generic in Java?

Cheng Chen :

Let's say we have a few test interfaces/classes like this:

abstract class Plant {
    public abstract String getName();
}

interface Eatable { }

class Apple extends Plant implements Eatable {
    @Override
    public String getName() {
        return "Apple";
    }
}

class Rose extends Plant {
    @Override
    public String getName() {
        return "Rose";
    }
}

interface Animal {
    <T extends Plant & Eatable> void eat(T plant);
}

You can see Animal.eat is a generic method with constraints. Now I have my Human class like this:

class Human implements Animal {
    @Override
    public void eat(Plant plant) {
    }
}

which compiles fine. You can see Human.eat is less constrained than Animal.eat because the Eatable interface is lost.

Q1: Why doesn't the compiler complain about this inconsistency?

Q2: If Plant&Eatable downgrades to Plant is acceptable for the compiler, why it complains on eat(Object plant)?

Ahmed Mazher :

Lesson: Generics by Gilad Bracha according to him

public static <T extends Object & Comparable<? super T>> T max(Collection<T> coll)

This is an example of giving multiple bounds for a type parameter, using the syntax T1 & T2 ... & Tn. A type variable with multiple bounds is known to be a subtype of all of the types listed in the bound. When a multiple bound is used, the first type mentioned in the bound is used as the erasure of the type variable.

so your example <T extends Plant & Eatable> void eat(T plant); will be erased to void eat(Plant plant); so when you override it the compiler doesn't complain

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=450779&siteId=1