Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - implements and extends

Tags:

java

generics

I am trying to write something like

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

and

public abstract class M<I extends P> extends R<I extends P> implements Q<I extends P> {}

but I am getting errors like Multiple markers and syntax error on token extends, expected. Please let me know what is the correct way of doing this.

like image 984
Shweta Avatar asked Oct 21 '10 07:10

Shweta


People also ask

Can you have implements and extends together in Java?

Yes. you can happily do it.

Can a generic class extend 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.

How are generics implemented in Java?

To implement generics, the Java compiler applies type erasure to: Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.


2 Answers

When you have interfaces in generics, you still have to use the extends keyword.

In your case, if you know what T will be :

public class A<T extends C> implements B<T> {}

If you don't and you simply have to implements B with a C type :

public class A implements B<C> {}

For the second part, once you've defined I you can use it as is in your other generic types :

public abstract class M<I extends P> extends R<I> implements Q<I> {}

Resources :

  • www.angelikalanger.com - Java Generics FAQs
  • Oracle.com - generics tutorial
like image 98
Colin Hebert Avatar answered Oct 24 '22 16:10

Colin Hebert


There is no implements keyword in generic bounds. It's only extends

Furthermore - you should specify the type parameter only in the class definition, and not in supertypes. I.e.

public class A<T extends C> implements B<T> {}
like image 34
Bozho Avatar answered Oct 24 '22 16:10

Bozho