Creating Packages
It may surprise you that we could create our own class
and java could make use of it. When we declared and/or instantiated
an object of a TimeBasics type, java automatically looked in the program's
directory for a TimeBasics.class. But developers don't want to
always locate everything accessing a class in the same directory.
You might have two or more user defined classes that you want to use in a
given Java program. Making sure all of these classes are compiled in
the program's directory is a lot of useless work! Fortunately, in Java, you can create packages that can be compiled to a particular directory and then accessed using an import statement in other programs. This webpage addresses how this can be done. All should be located further along the path c:\j2sdk1.4.0\jre\classes
You are certainly likely to want to add more subdirectories to this path, but this is putting you in the direction where they should be located. You are likely to need to create this classes directory along that path. This is the default path for the location of user-defined classes that are being packaged. For this particular program you also need to create a subdirectory of this directory called javaPackages and a subdirectory of this called TimeClasses. I make use of the directory javaPackages along this path to contain directories for each of my packages. This is illustrated in the following image. |
Now the code for TimeBasics.java should be altered slightly to include a package statement. Notice the package statement. package javaPackages.TimeClasses; |
package javaPackages.TimeClasses; import java.text.DecimalFormat; // This class maintains the time in a 24 hour format // and has a method to convert this to an AM/PM scale public class TimeBasics extends Object {
} |
This is the only change that is required to the program . In order to compile this class and locate it appropriately along the path you need to give the command javac -d C:\j2sdk1.4.0\jre\classes TimeBasics.java This will cause the TimeBasics.class to be located along the path C:\j2sdk1.4.0\jre\classes\javaPackages\TimeClasses\ because of the path specified in the compilation command and the package statement package javaPackages.TimeClasses; as you can see in the following image. |
Now to get our TimeBasicsTest to compile and be able to access the TimeBasics class you need to include an additional statement. import javaPackages.TimeClasses.TimeBasics; This will allow you to have the TimeBasicsTest be in any other directory and still appropriately access the TimeBasics class. The revised code for TimeBasicsTest.java follows. |
import javax.swing.*; import java.awt.*; import java.awt.event.*; import javaPackages.TimeClasses.TimeBasics; public class TimeBasicsTest extends JApplet implements ActionListener {
} |
Now the code will run wherever you want it to on the
same machine. You do not need to specify any special path in the
compilation command.
and
will still work. |