Java: Packages

Posted February 15, 2006 by William_Wilson in Java programming

Now you can arrange your files like a pro by using your own packages to clean up your class files. The following tutorial explains the steps necessary to accomplish this.

Have you ever wanted to clean up a folder FULL of .class files, and sort them into folders based on their use? Perhaps you have simply wanted to put the program into a folder so all that is visible is a single .exe, or .bat, or .java. Here are the required steps:

All you need is a few lines. In the example below, these class files are used:

Suppose I want to put program and GUI into folders based on their use and leave run at the same level as these folders.
I will assume that GUI and program do not need to know about each other, and run needs access to both.
Ending File Heirarchy:
PROGRAM <--this is a folder | ---------program.class GUI <----this is a folder | -----------GUI.class NOTE: As long as you do not wish to modify a .class file, AND it is not needed to run your program, the corresponding .java file is not necessary and can be deleted.

To accomplish this, do the following:
This is used as the first line, and it MUST be the first line of any class.
Then add the following line:
Package GUI;
*Now compile, and the folder GUI will be created with the GUI.class file inside it.
Use this as the first line, and it MUST be the first line of any class.
Add the line:
Package Program;
*Now compile, and the folder Program will be created with the program.class file inside it.
We must now tell this file where to find the .class files we just moved.
Simply add the following to the rest of your imports:
import GUI.*;
import Program.*;

NOTE some compilers do not like the * operator on personal packages, and you may have to do the following:
import GUI.GUI;
import Program.program;

The .class files will still be listed inside the original folder, but I assure you they are no longer needed.
Compile run. java, and you are done.

Questions/Comments: [email protected]
-William. ยง (marivn_gohan)

The Conversation

Follow the reactions below and share your own thoughts.