Search code examples
javapackageclasspathjavac

Using external class files in a package


I have a program that uses an external library called JHelper located in a neighboring folder

home
|--lib
|  |--JHelper.java
|  `--JHelper.class
`--prj
   `--HelloWorld.java

The HelloWorld.java file

//package prj

public class HelloWorld {
    public static void main(String[] args) {
        String echoed = JHelper.echo("Hello World");
        System.out.println(echoed);
    }
}

I can compile HelloWorld.java with javac by providing JHelper's location in the CLASSPATH like so,

PS ~\prj> javac -classpath ".;..\lib\" HelloWorld.java

However if I uncomment package prj to HelloWorld.java then the javac outputs that it cannot find the symbol JHelper

Why does making HelloWorld.java a package prevent javac from finding JHelper on the CLASSPATH?


Solution

  • Because a class A can only use a class B without importing it (or its whole package) if the other class B is in the same package as A (or is in the java.lang package).

    But... you can't import classes from the default package.

    So the simple rule to follow is: never put classes in the default package.