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)
?
Any class that implements a generic interface must itself be generic. And on the next page (emphasis mine): In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface.
Yes, you can define a generic method in a non-generic class in Java.
Code Reuse: With help of Generics, one needs to write a method/class/interface only once and use it for any type whereas, in non-generics, the code needs to be written again and again whenever needed.
Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With