Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 618
Cheng Chen Avatar asked Aug 10 '16 02:08

Cheng Chen


People also ask

Can a generic class implement a non generic interface?

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.

Can you define a generic method in a non generic class in Java?

Yes, you can define a generic method in a non-generic class in Java.

What is difference between generic and non generic 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.

Can a generic implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.


1 Answers

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

like image 113
Ahmed Mazher Avatar answered Oct 19 '22 01:10

Ahmed Mazher