h4ck3d
h4ck3d

Reputation: 6364

what does this interface declaration mean in java?

It might be a noob question but I am learning java and I came across an interface which had its definition like :

public interface MyClass <T extends Comparable<T>>

Can someone please explain what does it mean? I mean what kind of interface is created.

Upvotes: 0

Views: 208

Answers (3)

Ignacio Manzano
Ignacio Manzano

Reputation: 131

It means that T must implement Comparable over the same object.

for example

public interface MyClass <T extends Comparable<T>>

en then you can use as follow

public class MyImpl implements MyClass<String>

It is valid because String implements Comparable. But the following sentence is not valid because MyNewImpl is not implementing Comparable.

public class MyNewImpl {}    
public class MyImplTwo implements MyClass<MyNewImpl>

Regards Ignacio

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

The interface takes a type T which is Comparable with other T.

The interface is much the same only its generic type is constrained.

Upvotes: 1

Neet
Neet

Reputation: 4047

It means that the generic type argument must implement the Comparable interface.

When specifying <T extends Comparable<T>> you can use e.g. Collections.sort in this interface on type T. Without extends you can not guarantee that T is comparable.

Numbers and String are e.g. comparable and implement the Comparable interface.

Upvotes: 4

Related Questions