Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - why is "extends T" allowed but not "implements T"?

I wonder if there is a special reason in Java for using always "extends" rather than "implements" for defining bounds of typeparameters.

Example:

public interface C {} public class A<B implements C>{}  

is prohibited but

public class A<B extends C>{}  

is correct. What is the reason for that?

like image 405
user120623 Avatar asked Jun 10 '09 15:06

user120623


People also ask

Should implements or extends appear?

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 a generic implement an interface?

Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

Can I use both extends and implements?

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


2 Answers

There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).

like image 133
Tetsujin no Oni Avatar answered Sep 22 '22 15:09

Tetsujin no Oni


The answer is in here :

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound […]. Note that, in this context, extends is used in a general sense to mean either extends (as in classes) or implements (as in interfaces).

So there you have it, it's a bit confusing, and Oracle knows it.

like image 29
MikaelF Avatar answered Sep 25 '22 15:09

MikaelF