How to allow interface implementation in only one package

I have package P with

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

Now I want to prohibit the implementation of I outside P , but I must be publicly available, since I use it for the public method(I parameter) .

How can I do that?

Is there any β€œfinal package” for this?

Have you ever had this situation?


Details:

I know about the possibility of using an abstract class only with private package constructors instead of the I interface, but S1 and S2 extend different classes, so I will need multiple inheritance (since simulated multiple inheritance (see, for example, "Effective Java Element 18") does not work )

+4
source share
3 answers

You can also try the following attempt:

Use a dummy batch private interface and create a method in your public interface that 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 can implement interface I All classes from outside will never be able to implement the Dummy getDummy() method. At the same time, classes outside the package will be able to use all other methods of the I interface that do not have a Dummy interface in their signature.

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

+7
source

Impossible to do this. If your interface is public , it can be implemented by anyone. Is it possible for your two implementations to extend the abstract class and encapsulate the ones they are currently expanding?

It’s better to ask if you really need to follow this rule. An interface point is that you should be able to accept and implement an interface. If you really need to, you can do the validation at the point of using the interface by checking that the fo class for the instance is one of the two that you allow.

+4
source

If you do split interface

 interface I 

it should make it accessible only from the package and class

http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

0
source

Source: https://habr.com/ru/post/1442353/


All Articles