Multi-Level Package Hierarchies
What you'll learn: How subpackages organize code into nested structures that mirror your project's directory layout.
Understanding Package Hierarchies
Just like organizing files into folders and subfolders on your computer, Java packages can be nested multiple levels deep. A multi-level package hierarchy uses dots (.) to separate each level, creating a logical structure that reflects the physical directory organization on disk.
When you declare a package like com.company.project.utilities, you're creating a four-level hierarchy. Each segment represents a directory:
src/
com/
company/
project/
utilities/
StringHelper.java
How Subpackages Work
Here's the crucial point: subpackages are independent packages. Even though com.company.project.utilities and com.company.project.database share a common prefix, they don't inherit visibility or access rights from each other. They're completely separate namespaces.
A class in com.company.project:
package com.company.project;
public class Main {
// Cannot directly access classes in com.company.project.utilities
// without importing them
}
To use a class from the subpackage, you must import it explicitly:
package com.company.project;
import com.company.project.utilities.StringHelper;
public class Main {
// Now StringHelper is accessible
}
The Directory-Package Contract
The directory structure must exactly match the package declaration. A file declaring package com.company.project.utilities must physically reside in the com/company/project/utilities/ directory relative to your source root.
Key Takeaway: Multi-level package hierarchies organize code into nested namespaces that mirror directory structures, but subpackages are independent—they don't automatically inherit access to each other's classes.