简体   繁体   中英

Restrict classes that can implement interface in Java

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?

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM