This section provides a tutorial example on how to import classes defined in an unnamed package to a named package. The imported class must be defined as 'public'.
Recently, I received an email from a reader asking me how to refer to a class
defined in an unnamed package if the calling class is in a named class with JDK 1.4.1.
To answer this question, let's enter a new class called "ImportingHelloCom" in a package called "com",
and run the following commands:
C:\hy\tmp>type com\ImportingHelloCom.java
/**
* ImportingHelloCom.java
* Copyright (c) 2004 by Dr. Herong Yang
*/
package com;
import Hello;
public class ImportingHelloCom {
public static void main(String[] a) {
System.out.println("Calling the imported Hello.main()...");
Hello.main(a);
}
}
C:\hy\tmp>type Hello.java
class Hello {
public static void main(String[] a) {
System.out.println("Hello world!");
}
}
C:\hy\tmp>del *.class
Could Not Find C:\hy\tmp\*.class
C:\hy\tmp>del com\*.class
Could Not Find C:\hy\tmp\com\*.class
C:\jdk1.3.1\bin\javac com\ImportingHelloCom.java
com\ImportingHelloCom.java:5: cannot resolve symbol
symbol: class Hello
import Hello;
^
com\ImportingHelloCom.java:9: cannot resolve symbol
symbol : variable Hello
location: class ImportingHelloCom
Hello.main(a);
^
2 errors
C:\jdk1.3.1\bin\javac -classpath . com\ImportingHelloCom.java
com\ImportingHelloCom.java:6: Hello is not public in empty package;
cannot be accessed from outside package
import Hello;
^
com\ImportingHelloCom.java:10: Hello is not public in empty package;
cannot be accessed from outside package
Hello.main(a);
^
com\ImportingHelloCom.java:10: main(java.lang.String[]) in Hello is
not defined in a public class or interface; cannot be accessed from
outside package
Hello.main(a);
^
3 errors
This test shows us that:
Only public classes in an unnamed package can be imported into named packages.
Comparing with the testing results from the previous sections, there is really
only one unnamed package. All classes defined without a package name are considered
to be in this single package. All classes can be imported into each other without
the "public" attribute.
To fix the last compilation error, just declare the Hello class as "public". Now let's
modify the classes and run the following commands:
C:\hy\tmp>type Hello.java
public class Hello {
public static void main(String[] a) {
System.out.println("Hello world!");
}
}
C:\hy\tmp>del *.class
Could Not Find C:\hy\tmp\*.class
C:\hy\tmp>del com\*.class
Could Not Find C:\hy\tmp\com\*.class
C:\jdk1.3.1\bin\javac -classpath . com\ImportingHelloCom.java
C:\jdk1.3.1\bin\java -classpath . com.ImportingHelloCom
Calling the imported Hello.main()...
Hello world!
As you can see, importing a class defined in an unnamed package into a class defined
in a named package is easy with JDK 1.3.1.