CypherAJ
CypherAJ

Reputation: 47

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?

Upvotes: 4

Views: 2901

Answers (4)

Dmitrii Semikin
Dmitrii Semikin

Reputation: 2584

In newer versions of Java "Sealed" classes and interfaces were added to control, which classes can implement interfaces and classes:

https://docs.oracle.com/en/java/javase/17/language/sealed-classes-and-interfaces.html#GUID-0C709461-CC33-419A-82BF-61461336E65F

Preview was first presented in Java 15 and since Java 17 they are fully supported.

Upvotes: 1

Artyom Dmitriev
Artyom Dmitriev

Reputation: 363

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.

Upvotes: 0

AbhishekAsh
AbhishekAsh

Reputation: 411

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.

Upvotes: 2

Tagir Valeev
Tagir Valeev

Reputation: 100339

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.

Upvotes: 3

Related Questions