15

Can someone tell me what the differences between the first and second codes are? MaxPQ stands for priority queue, which is a collection of "Key" objects that can be compared with each other.

Code 1:

public class MaxPQ<Key extends Comparable<Key>>{
...
}

Code 2:

public class MaxPQ<Key implements Comparable<Key>>{
...
}

The second code doesn't compile, but it is not intuitive to me why we need to extend instead of implement interfaces when using a generic.

Popcorn
  • 5,188
  • 12
  • 54
  • 87
  • 2
    A similar question can be found in [here][1]. [1]: http://stackoverflow.com/questions/976441/java-generics-why-is-extends-t-allowed-but-not-implements-t – krakover Jun 10 '12 at 20:21

3 Answers3

13

The difference is pretty straightforward: second code snippet does not compile and never will. With generics you always use extends, for both classes and interfaces. Also super keyword can be used there, but it has different semantics.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • @MarkX: not really, this is how generics were designed and specified. Simplicity? – Tomasz Nurkiewicz Jun 10 '12 at 20:02
  • 4
    @Mark One reason is: `Key` could be an interface itself and suddenly it would be `extends` again even though Comparable is an interface. So since you can't get it absolutely right in all cases, just being consistently inconsistent was preferred. – Voo Jun 10 '12 at 20:32
1

There is no implements in generics. The second code is invalid. You probably confusing with :

public class MaxPQ implements Comparable<Key> {
   ...
}
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
0

I assume it was decided to use extends for both interfaces and classes, because in the case of generic class declaration it does not make any difference is type argument bound to interface or to class.

Of course meaning of extends is quite different from its typical usage in class definition. Angelika Langer do have nice text about different meanings of extends in Java: Does "extends" always mean "inheritance"?

Mikko Maunu
  • 41,366
  • 10
  • 132
  • 135