tags:

views:

2477

answers:

3

Hi folks,

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?

+5  A: 

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 the class to operate with assignable to that another (extends), or is this class assignable from that one (super).

Tetsujin no Oni
+2  A: 

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

Tom Hawtin - tackline
+3  A: 

Probably because for both sides (B and C) only the type is relevant, not the implementation. In your example

public class A<B extends C>{}

B can be an interface as well. "extends" is used to define sub-interfaces as well as sub-classes.

interface IntfSub extends IntfSuper {}
class ClzSub extends ClzSuper {}

I usually think of 'Sub extends Super' as 'Sub is like Super, but with additional capabilities', and 'Clz implements Intf' as 'Clz is a realization of Intf'. In your example, this would match: B is like C, but with additional capabilities. The capabilities are relevant here, not the realization.

beetstra
Tom Hawtin - tackline