Domanda

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

È stato utile?

Soluzione

  1. 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 that X is assignable to type Y - in the end it's immaterial whether Y is an interface or a class, so making you use implements or extends based on whether Y is the one or the other seems like a hassle.
  2. 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.

Altri suggerimenti

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> {
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top