开发者

Restrict the classes that may implement an interface

开发者 https://www.devze.com 2023-02-12 02:04 出处:网络
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:

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<Q开发者_StackOverflowux> {} // 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!


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.


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.


The only way you could limit who can implement your interface is by controlling visibility of your interface using visiblity modifiers: public, protected, private or the default one (package).

0

精彩评论

暂无评论...
验证码 换一张
取 消