This section provides a tutorial example on how to import classes defined in an unnamed package to a named package with JDK 1.4.1. A wrapper class is needed to integrate the class in an unnamed package into a named package with JDK 1.3.1 first.
As we learned earlier in this chapter, if we re-run the previous test with JDK 1.4.1,
we will get a compilation error on the "import Hello" statement.
In this case, if you try my earlier suggestion of removing the import statement,
you will get another compilation error about not able to resolve the class name "Hello",
because it is not defined in the same package as the calling class.
How to resolve this problem? I am suggesting two options:
If you have the source code of the class to be imported from the unnamed package,
you can modify the class to put it in a named package.
If you don't have the source code of the class to be imported from the unnamed package,
you can create a new class in a named package to wrapper the to-be-imported class and
compile it with JDK 1.3.1. The wrapper class can then be easily imported into any class
with JDK 1.4.1.
To approve my second option, let's continue with our previous tests,
enter a wrapper class called HelloWrapper in a package called wrapper,
then run the following commands:
C:\hy\tmp>type wrapper\HelloWrapper.java
/**
* HelloWrapper.java
* Wrapping Hello class from the unnamed package into a named package
* To be compiled with JDK 1.3.1.
* Copyright (c) 2004 by Dr. Herong Yang
*/
package wrapper;
import Hello;
public class HelloWrapper {
public static void main(String[] a) {
System.out.println("Wrapping Hello classs...");
Hello.main(a);
}
}
C:\hy\tmp>type com\ImportingHelloWrapperCom.java
/**
* ImportingHelloWrapperCom.java
* Copyright (c) 2004 by Dr. Herong Yang
*/
package com;
import wrapper.HelloWrapper;
public class ImportingHelloWrapperCom {
public static void main(String[] a) {
System.out.println("Calling the imported Hello.main()...");
HelloWrapper.main(a);
}
}
C:\jdk1.3.1\bin\javac -classpath . wrapper\HelloWrapper.java
C:\j2sdk1.4.1\bin\javac -classpath . com\ImportingHelloWrapperCom.java
C:\j2sdk1.4.1\bin\java -classpath . com.ImportingHelloWrapperCom
Calling the imported Hello.main()...
Wrapping Hello classs...
Hello world!
As you can see from the output, the problem is perfectly resolved by using both of versions
of JDK together. So after you installed JDK 1.4.1, don't delete JDK 1.3.1, you might need
it one day!