DaveFar DaveFar - 1 year ago 83
Java Question

How to only allow implementations of an interface in the same package

I have a package


  • public interface I

  • public class S1 extends Foo implements I

  • public class S2 extends Bar implements I

Now I want to forbid implementations of
outside of
, but
should be public, since I use it for a
public method(I parameter)

How can this be done?

Is there some "package-final pattern" for this?

Did you ever have such a situation?


I'm aware of the possibility of using an abstract class with only package private constructors instead of interface
, but
extend different classes, so I would need multiple inheritance (since simulated multiple inheritance (see e.g. Effective Java item 18) does not work here).

Answer Source

You could also try the following attempt:

Use a dummy package private interface and create a method in your public interface which returns it. Like this:

public interface I {
  Dummy getDummy(); // this can only be used and implemented inside of the 
                    // current package, because Dummy is package private
  String methodToUseOutsideOfPackage();

interface Dummy {}

Thanks to this, only classes from the current package will be able to implement interface I. All classes from outside will never be able to implement the method Dummy getDummy(). At the same time the classes from outside of the package will be able to use all other methods of the interface I which do not have the Dummy interface in their signature.

This solution isn't beautiful, because you have one useless method in your interface I, but you should be able to achieve what you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download