By: Manoj Kumar Printer Friendly Format
While Java packages solve many problems from an access control and name-space-collision perspective, they cause some curious difficulties when you compile and run programs. This is because the specific location that the Java compiler will consider as the root of any package hierarchy is controlled by CLASSPATH. Until now, you have been storing all of your classes in the same, unnamed default package. Doing so allowed you to simply compile the source code and run the Java interpreter on the result by naming the class on the command line. This worked because the default current working directory (.) is usually in the CLASSPATH environmental variable defined for the Java run-time system, by default. However, things are not so easy when packages are involved. Here's why.
Assume that you create a class called PackTest in a package called test. Since your directory structure must match your packages, you create a directory called test and put PackTest.java inside that directory. You then make test the current directory and compile PackTest.java. This results in PackTest.class being stored in the test directory, as it should be. When you try to run PackTest, though, the Java interpreter reports an error message similar to "can't find class PackTest." This is because the class is now stored in a package called test. You can no longer refer to it simply as PackTest. You must refer to the class by enumerating its package hierarchy, separating the packages with dots. This class must now be called test.PackTest. However, if you try to use test.PackTest, you will still receive an error message similar to "can't find class test/PackTest."
The reason you still receive an error message is hidden in your CLASSPATH variable. Remember, CLASSPATH sets the top of the class hierarchy. The problem is that there's no test directory in the current working directory, because you are in the test directory, itself.
You have two choices at this point: change directories up one level and try java test.PackTest, or add the top of your development class hierarchy to the CLASSPATH environmental variable. Then you will be able to use java test.PackTest from any directory, and Java will find the right .class file. For example, if you are working on your source code in a directory called C:\\myjava, then set your CLASSPATH to .;C:\\myjava;C:\\java\\classes
Most Viewed Articles (in Java )
Latest Articles (in Java)
Comment on this tutorial
- Data Science
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews