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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With