Restrict classes that can implement interface in Java

感情迁移 提交于 2019-12-24 04:45:10

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/33007574/restrict-classes-that-can-implement-interface-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!