Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict the classes that may implement an interface

Tags:

java

generics

Generally speaking, is it possible to restrict the classes that may implement an interface?

More specifically, can a generic interface Foo<T> restrict its implementations to descendants of T:

interface Foo<T> {}
class Baz extends Bar implements Foo<Bar> {} // desirable
class Baz extends Bar implements Foo<Qux> {} // undesirable

The context is that Foo<Bar> objects should be castable to Bar objects in a type-safe way.

Having exhausted all other sources of information, I already have a strong hunch that this isn't possible—but I would be delighted if someone could prove otherwise!

like image 849
eggyal Avatar asked Feb 18 '11 11:02

eggyal


2 Answers

If the ability to cast is not strictly necessary, then adding an additional method like this to your interface might suffice:

public T getT()

If most implementations actually extend T, they can simply return this as the implementation of that method.

like image 109
Joachim Sauer Avatar answered Sep 23 '22 09:09

Joachim Sauer


Following shows me a compilation error on line 7, so I assume this is what you want, right?

1 public interface Foo<T extends Bar> {}
2
3 public class Bar{}
4 public class Qux{}
5
6 class Baz extends Bar implements Foo<Bar> {}
7 class Baz2 extends Bar implements Foo<Qux> {}

Also, consider Joachim's advice (why cast, just use T). It is how generics were intended to be used.

like image 28
mindas Avatar answered Sep 23 '22 09:09

mindas