Packages

Objectives

  • Create a package in Java
  • Use a self-made package in Java

Packages

When you have only a few programs written and are just learning Java or experimenting, it makes sense to keep those few files in one directory such as C:\myjava. As you develop more classes, you will find that it really pays to take time to organize them into what are referred to as packages. This helps keep class names unique because they are differentiated by the package they are in. Packages correlate directly to folders/directories. You put related classes in one folder and turn that folder of related classes into a package. Packages are often organized in a hierarchical structure.

Add-on classes are often stored in a subdirectory of the Java runtime, such as:

C:\Program Files\Java\jre1.8.0_20\lib\ext

The first step is to add a line at the very beginning of the source code (before the import statements) to tell the compiler that this class is part of a particular package. The statement tells the compiler what subfolder to put the package in. In the example below, the class will be placed in the com/klickfamily/util subdirectory relative to the current directory. The package statement must be the first Java statement in the source file. Comments and blank lines only are allowed before the package statement.

The next step is to compile the source, which will create any needed subfolders, and place the compiled class file in the appropriate spot. The compile command requires arguments that tell it that it is compiling a class intended for a package, and what folder packages descend from. The following line was used to compile the previous example:

javac -d C:\Temp Message.java

The Message.class file should now be located in C:\Temp\com\klickfamily\util. The next example shows how the Message class is imported so it can be used. It is compiled and run just like any other application that we have written so far except that we have to tell the compiler where the extra class files are located.

javac -classpath C:\Temp TestPackage1.java

The final step is to run the program, specifying where the classes can be found.

java -classpath ".;C:\Temp" TestPackage1

Hopefully, the above examples can get you started using packages. They are a great way to organize your classes. Better yet... use an IDE like Netbeans or Eclipse to do a lot of the detail work automatically.