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.
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.
super is a lower bound, and extends is an upper bound.
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.
Yes, you can. But you need to declare extends before implements : public class DetailActivity extends AppCompatActivity implements Interface1, Interface2 { // ... }
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.
There is no implements in generics. The second code is invalid. You probably confusing with :
public class MaxPQ implements Comparable<Key> {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With