- Can't speak for the designers of Java generics, but presumably they did this to simplify the language. The point of an
X extends Y
constraint is that we want to specify thatX
is assignable to typeY
- in the end it's immaterial whetherY
is an interface or a class, so making you useimplements
orextends
based on whetherY
is the one or the other seems like a hassle. - Try:
public class Foo<T extends Comparable<T>> implements Face<T>
- Face is an interface with a type parameter, so you need to fill in that type parameter when extending the interface.
Weird Generics Behaviour with Interface
-
03-07-2022 - |
Question
I want to create a generic class that takes elements of some generic type that are comparable. So I do:
public class Foo<T extends Comparable<T>>
and inside the class Foo
I have things like:
public void bar(T t)
and I'm assured that I can write code like this: t.compareTo(v)
.
Question 1: Why when using generics we have extends
instead of implements
for an interface? Comparable
is not a class.
\\
Assume now that I want to create another similar class to the above also implementing
the bar
method. I thought of creating this interface:
public interface Face<T extends Comparable<T>> {
public void bar(T t);
}
and then I change class Foo
to implement Face
(public class Foo<T extends Comparable<T>> implements Face
).
Question 2: When doing this I get the following compile error:
The method bar(T) of type Foo must override or implement a supertype method.
Why is this?
When I tell Eclipse to add the unimplemented methods
I get:
public void bar(Comparable t)
instead of ... bar(T t)
.
Solution
OTHER TIPS
Please re-format your question a bit. But if I understood anything there, do this:
// Face<T>, not just Face
public class Foo<T extends Comparable<T>> implements Face<T> {
}