Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implements vs extends in generics in Java

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.

like image 898
Popcorn Avatar asked Jun 10 '12 19:06

Popcorn


People also ask

What is difference between implement and extend in Java?

Difference: implements means you are using the elements of a Java Interface in your class. extends means that you are creating a subclass of the base class you are extending. You can only extend one class in your child class, but you can implement as many interfaces as you would like.

What is difference between extends and super in generics?

super is a lower bound, and extends is an upper bound.

Should implements or extends first?

The extends always precedes the implements keyword in any Java class declaration. When the Java compiler compiles a class into bytecode, it must first look to a parent class because the underlying implementation of classes is to point to the bytecode of the parent class - which holds the relevant methods and fields.

Can we use both extends and implements together in Java?

Yes, you can. But you need to declare extends before implements : public class DetailActivity extends AppCompatActivity implements Interface1, Interface2 { // ... }


2 Answers

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.

like image 106
Tomasz Nurkiewicz Avatar answered Oct 16 '22 11:10

Tomasz Nurkiewicz


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

public class MaxPQ implements Comparable<Key> {
   ...
}
like image 27
fastcodejava Avatar answered Oct 16 '22 13:10

fastcodejava