Search code examples
javaoopinheritance

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?


Solution

  • 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.