2

In Java 9, can I split sub-packages across modules? For example, can I have com.example.foo in one module and com.example.foo.bar in another module?

This seems like a simple question, but for some reason I'm not able to find a direct answer after some searching. An authoritative reference would be appreciated.

I assume I can have sibling sub-packages in different modules, e.g. com.example.foo and com.example.other.

Naman
  • 27,789
  • 26
  • 218
  • 353
Garret Wilson
  • 18,219
  • 30
  • 144
  • 272
  • 1
    Maybe trying this could be worth it, execute [`getPackages()`](https://docs.oracle.com/javase/9/docs/api/java/lang/Package.html#getPackages--) and you would find them as two different packages. To my knowledge, there is no convention such as sub-package in the JavaDocs either. – Naman Jun 16 '18 at 17:41
  • 1
    IMHO, this tends to be a duplicate as marked unless specified for any such difference found in the implementations of packages in the mentioned version. – Naman Jun 16 '18 at 17:44

1 Answers1

8

There's no such thing as a "sub-package". my.package and my.package.sub have nothing more in common than any two random packages: they just have similar names. See this answer which starts

In reality there is no such thing as a sub-package in Java

That being the case, yes you can include them in different modules.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • 2
    I am aware that this is the traditional view of packages, but I want to confirm that this conception is still valid after the introduction of the module system, which invalidated a lot of assumptions that had been in place in previous versions. Do you have an authoritative reference that takes the new module system into account? – Garret Wilson Jun 16 '18 at 17:02
  • 2
    The module system doesn't change any of the semantics of packages, and I don't know why you're under the impression that it would. What you're proposing doesn't really make sense because two **distinct** modules should not need to contain **related** packages, but there's nothing to stop you from doing so. – Michael Jun 16 '18 at 17:38
  • I am not "under the impression that it would". That's why I asked the question: I didn't know. Thanks for helping to clarify. – Garret Wilson Jun 20 '18 at 19:05
  • 3
    While I respect the fair point that "there's no such thing as a sub-package," I think it's legitimate, for someone who doesn't understand the full spec, to ask this question and expect an answer with references to documentation or a working example. Marking this as a duplicate of a completely unrelated question, closing it from further answers, is, in my opinion, also not helpful (that's on nullpointer, not Michael). It was suggested that https://stackoverflow.com/questions/54370999 is a duplicated of this question, but since this question has been closed, I have added a detailed answer there. – Nick Williams Jan 25 '19 at 20:03