Search code examples
javajava-package

Can't import subpackage into another subpackage


I am trying to create a package named myUtil, inside I have two subpackages named Node and BinaryTree.

Inside Node dir, I have Node.java and Node.class, and of course the first line in the java file is:

package myUtil.Node;

Now, in BinaryTree.java, located in BinaryTree directory, I would like to import Node.class to use it.
This is the code:

package myUtil.BinaryTree;

import myUtil.Node.Node;

public class BinaryTree {
    public Node root;
}

When I try to compile it, it gives me this error:

BinaryTree.java:3: error: package myUtil.Node does not exist
import myUtil.Node.Node;
                  ^

Also, I tried

import myUtil.Node;
import myUtil.Node.*;

but it still gives me this error...

Edit: As requested, I'm sharing the whole code.

This is Node.java:

package myUtil.Node;

public class Node {
    int value;
    Node left, right;

    public Node(int value) {
        this.value = value;
        left = null;
        right = null;
    }
}

And this is BinaryTree.java:

package myUtil.BinaryTree;

import myUtil.Node.Node;

public class BinaryTree {
    public Node root;
}

I'm compiling these files directly in their respective folders, using:

javac filename.java

Solution

  • Java doesn't support "sub"-packages. Even if packages are organized as in java, java.net, java.util, each of them is an individual package - although on the disk packages are organized as folders and subfolders.

    And you don't import packages but only classes or methods.

    So in your description, to use the class Node from the package myUtil.Node in another package, you would need to import myUtil.Node.Node;

    If you want to use Node in a class within the same package (same folder on disk), you don't need to import that.

    An import like import myUtil.Node.*; imports all classes of the myUtil.Node package, but none of any package that starts with myUtil.Node. (what you mentioned as "sub"-package). Java doesn't support such imports (like from a folder and all subfolders).

    To your specific situation: Java has a naming convention to use only lowercase letters in package names - convention means, you don't have to do it like that, but it is better if you do because other developers will understand your code faster. (And also we on StackOverflow can help better for you next questions ;-)

    Also not every class has to be put into a separate package.

    So for you, probably a package myutils with the two classes Node and BinaryTree would be fine - and you don't have to import Node into BinaryTree then, as they would be both contained in the same package.