Recipe 23.1 Creating a Package


You want to be able to import classes and/or organize your classes, so you want to create your own package.


Put a package statement at the front of each file, and recompile with -d.


The package statement must be the very first noncomment statement in your Java source file preceding even import statements and it must give the full name of the package. Package names are expected to start with your domain name backward; for example, my Internet domain is, so most of my packages begin with com.darwinsys and a project name. The utility classes used in this book are in one of the com.darwinsys packages listed in Recipe 1.5, and each source file begins with a statement, such as:

package com.darwinsys.util;

Once you have package statements in place, be aware that the Java runtime, and even the compiler, will expect the class files to be found in their rightful place, that is, in the subdirectory corresponding to the full name somewhere in your CLASSPATH settings. For example, the class file for com.darwinsys.util.FileIO must not be in the file FileIO.class in my class path but must be in com/darwinsys/util/FileIO.class relative to one of the directories or archives in my CLASSPATH. Accordingly, it is customary to use the -d command-line argument when compiling. This argument must be followed by a directory name (often . is used to signify the current directory) to specify where to build the directory tree. For example, I often say:

javac -d . *.java

which creates the path (e.g., com/darwinsys/util/ ) relative to the current directory, and puts the class files into that subdirectory. This makes life easy for subsequent compilations, and also for creating archives, which I will do in Recipe 23.4.

Note that a change was made to the compiler in JDK 1.4 such that classes that do not belong to a package (the "anonymous package") cannot be listed in an import statement, although they can be referred to by other classes in that package.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: