JDK (Java Development Kit) Tutorials
Dr. Herong Yang, Version 5.00

Importing Classes Defined in Unnamed Packages

This section provides a tutorial example on how to import classes defined in an unnamed package - done in the same as importing classed defined in named packages with JDK 1.3.1. But it is not allowed with JDK 1.4.1.

For classes defined in unnamed packages, their simple names are identical to their fully qualified names. Therefore, there is no need to use import statement in the compilation units where they are referred.

But if you really want to use an import statement, it shouldn't be a problem. So let's enter another class, ImportingHello.java, in C:\hy\tmp directory, and run the following commands to see what happens with the import statement:

C:\hy\tmp>type ImportingHello.java
/**
 * ImportingHello.java
 * Copyright (c) 2003 by Dr. Herong Yang
 */
import Hello;
public class ImportingHello {
   public static void main(String[] a) {
      System.out.println("Calling the imported Hello.main()..."); 	
      Hello.main(a);
   }
}

C:\hy\tmp>del *.class
Could Not Find C:\hy\tmp\*.class

C:\hy\tmp>del ..\src\*.class
Could Not Find C:\hy\src\*.class

C:\hy\tmp>\jdk1.3.1\bin\javac -classpath ..\src ImportingHello.java

C:\hy\tmp>\jdk1.3.1\bin\java -classpath .;..\src ImportingHello
Calling the imported Hello.main()...
Hello world!

C:\hy\tmp>del *.class

C:\hy\tmp>del ..\src\*.class

As you can see, there is no problem. The import statement makes no impact on the compilation and execution processes with JDK 1.3.1.

However, the import statement will cause compilation problem if we use JDK 1.4.1, see the following commands and outputs:

C:\hy\tmp>\j2sdk1.4.1\bin\java -version
java version "1.4.1_01"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)

C:\hy\tmp>\j2sdk1.4.1\bin\javac -classpath ..\src ImportingHello.java
ImportingHello.java:5: '.' expected
import Hello;
            ^
1 error

Obviously, specification on import statement has been changed. With JDK 1.4.1, import statement can not be used on compilation units in unnamed packages. So, from now on, stop use import statements on classes or interfaces defined in unnamed packages.

Sections in This Chapter

What Is an Unnamed Package?

One Class in an Unnamed Package - Hello.java

Two Classes in Unnamed Packages - Hello.java and CallingHello.java

Importing Classes Defined in Unnamed Packages

Importing Classes from Unnamed to Named Packages

Importing Classes from Unnamed to Named Packages - JDK 1.4.1

Dr. Herong Yang, updated in 2008
Importing Classes Defined in Unnamed Packages