1

This question has been asked similary here: Java: Subpackage visibility?

My current package structure is:

src/
 |   library/
 |   |    InterfaceA.java
 |   |    ClassB.java
 |   |    provider/
 |   |    |    ClassofInterfaceA.java
 |   user/
 |   |    UsageOfClassofInterfaceA.java

So the ClassOfInterfaceA.java uses Methods from ClassB.java and implements the Interface.java.

Our user, who has created the class UsageOfClassOfInterfaceA.java, should only be able to access methods from ClassOfInterfaceA.java. He shouldn't be able to access any class/interface/variable or method from the Library package.

Since the answers of the linked question more aim towards the junit tests and how the IDE uses those, I couldn't find any answers.

Please don't recommend any other package structure since this is predefined by our lecturer.

Thanks in advance :)

EDIT: since it has been asked, all the classes are currently public, because I can't address them through my ClassOfInterfaceA.java. I also have to use Java8.

To address the factory, the ClassOfInterfaceA.java will be used by an UI to demonstrate their usage. So UsageOfClassOfInterfaceA.java is essentially a UI class.

Scorix
  • 487
  • 6
  • 20

1 Answers1

0

First of all, your initial approach is wrong: classes represent implementation details. So you want your users to solely rely on interfaces. Thus you should rather expose that interface, not some class implementing it.

So, the interface goes public, the other classes go private or package protected. And from that point of view, you also organize your file/package layout: the things that should be exposed should be put in the same spot.

The other thing you need to add: some sort of factory that allows "user" code to acquire an instance of said interface (as said, the user class should not know the name of that implementation class, so it can't do a new() call itself).

Finally: you should understand that Java 9 added the module concept, allowing even more options to consider.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • could you provide an example for the factory? Also, the Interface shouldn't be available for the user, since they shouldn't be able to provide any self implemented classes, basically the interface is only there so the developer for the library can implement differents ways of the use of this interface – Scorix Oct 29 '18 at 18:43