Search code examples
javajava-package

How to write package-statements for nested packages?


If I have a class in a sub-package like sub-package-name, which is in a parent-package like higher-level-package-name, do I just write

package "sub-package-name";

Or also add the parent-package, maybe like

package "sub-package-name";
package "higher-level-package-name";

Solution

  • Example

    You are only supposed to write a single package statement, with the full name of the package. So if you have a directory hierarchy for your packages like:

    foo/
    └─ bar/
       └─ baz/
          └─ Test.java
    

    Your Test.java file would have a statement like:

    package foo.bar.baz;
    

    Nested packages

    Java itself actually has no concept of nested packages.

    As far as the language is concerned,

    • foo,
    • foo.bar and
    • foo.bar.baz

    are considered three independent packages. Sub-packages or parent-packages are not a thing to Java.

    Consequently, package-visibility also does not carry over to sub- or parent-packages.