Restrict classes that can implement interface in J

2019-07-08 07:51发布

Before we start: I'm aware of this question and in my case that answer will not work.

So let's say I have:

interface Iface
class SuperClass (this one is from external library and can't be changed)
class SubClass extends SuperClass
class OtherClass

Is there a way to make it so that Iface can only be implemented by SuperClass and its subclasses? So in this case:

class SuperClass implements Iface - would be good if I could edit that class
class SubClass implements Iface   - good
class OtherClass implements Iface - bad

Side question: is that against OOP principles or is it a sign of bad code to do so?

3条回答
该账号已被封号
2楼-- · 2019-07-08 08:38

The only option I see is to make the interface package-private and implement it by public SuperClass which is located in the same package. This way the users of your package will be able to subclass the SuperClass, but not able to implement your interface directly. Note though that this way the interface itself becomes not very useful as nobody outside can even see it.

In general it seems that your problem can be solved just by removing the interface and replacing it everywhere with SuperClass.

查看更多
Viruses.
3楼-- · 2019-07-08 08:43

I believe and referring JavaDocs, A public interface cant be stopped from being inherited. An interface by definition is designed to work that way and we have access specifiers and stuffs in Java to make a Interface with lesser visibility. Would love to shown a way though.

查看更多
beautiful°
4楼-- · 2019-07-08 08:46

Although I absolutely agree with @Tagir's answer (and believe it should be accepted), to be fair one can make restrictions on what classes can implement what interfaces in runtime if he uses his own implementation of ClassLoader. Also, I think such a thing can be done in compile time if one builds his own JVM-based language.

查看更多
登录 后发表回答