Wong Jia Hau
Wong Jia Hau

Reputation: 3069

When will I need to implement a generic interface with different types?

Background

One of the well-known interfaces in Java/C# is the Comparable<T> interface. When one wants to implements it, the usual case is to set the type parameter to the type of the implementer. For example,

class Person implements Comparable<Person> { /*body*/ }

Such an interface is useful for generic functions, such as sort:

<T extends Comparable<T>> T[] sort(T[] xs) { /*body*/ }

Questions

Since it seems like we almost use the same type to implement the interface (as demonstrated in Background), when would we set the type parameter to be different type than the implementer?

For example:

class A implements AnInterface<B> { /*body*/ }

So, I'm looking for answers for the following questions:

  1. What is the use case for such a scenario?
  2. What are the alternatives to such use cases?

Upvotes: 0

Views: 82

Answers (1)

xuq01
xuq01

Reputation: 587

When your class is an implementation of some specific case of a more generic interface, this can occur occasionally.

For example, in persistent data structures, integer maps have a more efficient representation than general maps (i.e. balanced binary trees). In this case, you might want to have something like:

class EfficientIntMap implements Map<Integer>

I am not sure what you mean by "alternatives". Certainly you do not have to inherit from such interfaces, and you don't have to use OOP at all.

Upvotes: 1

Related Questions