Creating a Package

Problem

You want to create your own package.

Solution

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

Discussion

The package statement must be the very first non-comment statement in your Java source file, preceding even import statements, and 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 darwinsys.com, so most of my packages begin with com.darwinsys and a project name. The utility classes used in this book are in the package com.darwinsys.util, and each source file begins with:

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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.