Java Reference
In-Depth Information
Example 3.23
Use of a
package
statement
package com.myco.financial;
public class
Account
{
// ...
}
Making a class part of a package is easy. What's tricky is putting the class
file in the right location so that Java can find it.
Think of the current directory as the root of your package tree. Each part
of a package name represents a directory from that point on down. So if you
have a package named
com.myco.financial
then you'll need a directory
named
com
and within that a directory named
myco
and within that a directory
named
financial
. Inside that
financial
directory you can put your
Account.class
file.
When Java runs a class file, it will look in all the directories named in the
CLASSPATH
environment variable. Check its current value:
$ echo $CLASSPATH
$
If it's empty, as in this example, then the only place where it will look for
your classes will be the current directory. That's a handy default, because it is
just what you want when your class file has no
package
statement in it. With
no
package
statement, your class becomes part of the
unnamed package
. That's
fine for simple sample programs, but for serious application development you'll
want to use packages.
Let's assume that you're in your home directory,
/home/joeuser
, and
beneath that you have a
com
directory and beneath that a
myco
directory with
two subdirectories
financial
and
util
. Then with your classes in those lower
level directories, you can run your Java program from the home directory.
If you want to run it from any arbitrary directory (e.g.,
/tmp
or
/home/joeuser/alt
) then you need to set
CLASSPATH
so it can find this
package tree. Try: