Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a package P with

  • public interface I
  • public class S1 extends Foo implements I
  • public class S2 extends Bar implements I.

Now I want to forbid implementations of I outside of P, but I 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?


Details:

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

like image 829
DaveFar Avatar asked Dec 15 '22 18:12

DaveFar


2 Answers

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.

like image 74
LuGo Avatar answered Jan 17 '23 06:01

LuGo


Can't do it. If your interface is public it can be implemented by anyone. Is it possible for your two implementations to extend an abstract class and encapsulate the ones they are currently extending?

Better question is do you REALLY need to enforce this rule. The point of an interface is that you should be able to accept and implementation of the interface. If you really need to, you could do the validation at the point of use of the interface by checking that the class fo the instance is one of the two that you allow.

like image 24
John B Avatar answered Jan 17 '23 06:01

John B