Amittai Aviram
Amittai Aviram

Reputation: 2311

Java Package Hierarchy: Middle Level Cannot Find Lower Level Despite Import Statement

I have defined a data structure that uses another, lower-level data structure, which I also defined. For tidiness, I want each data structure to have its own directory and package name. Suppose the higher-level data structure's package is called packageA and the lower-level packageB. Then, I want to use the data structure defined in packageA in a program-say, Program. So I have a directory structure like this:

Program
 |- Program.java
 |- packageA
     |- ClassA.java
     |- packageB
         |- ClassB.java

ClassB.java has at the top

package packageB;

ClassA.java has at the top

package packageA;
import packageB.ClassB;

And then Program.java has import packageA; and refers to ClassA in its code.

When I try to compile at the top level with javac *.java, I get the error that package packageB does not exist.

What am I doing wrong, and how can I accomplish this simple goal? Thank you.

Upvotes: 1

Views: 76

Answers (1)

ernest_k
ernest_k

Reputation: 45309

Your import statement in ClassA.java is wrong. The import statement for a type has to be its canonical name. Here's what JLS 7.5.1 says:

7.5.1. Single-Type-Import Declarations
A single-type-import declaration imports a single type by giving its canonical name, making it available under a simple name in the module, class, and interface declarations of the compilation unit in which the single-type-import declaration appears.
The TypeName must be the canonical name of a class type, interface type, enum type, or annotation type (§6.7).

And the relevant definition for canonical name in section 6.7 is

The fully qualified name of a named package that is a subpackage of another named package consists of the fully qualified name of the containing package, followed by ".", followed by the simple (member) name of the subpackage.

This does not make it possible to use relative package names to import. Your import statement must be

import packageA.packageB.ClassB;

And the package declaration in ClassB.java itself must be

package packageA.packageB;

I'm assuming that Program is not a package;

Upvotes: 1

Related Questions