A package is, essentially, a grouping of classes. A package is a namespace that organizes a set of related classes and interfaces Defining a Package To create a package is quite easy: simply include a package command as the first This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Java uses file system directories to store packages. For example, the .class files for any class that is declared to be part of MyPackage must be stored in a directory called MyPackage. The directory name must match the package name exactly. More than one file can include the same package statement. The package statement simply specifies to which package the classes defined in a file belong. It does not exclude A package hierarchy must be reflected in the file system of the Java development system. For example, a package declared as package java.awt.image; needs to be stored in java/awt/image, java\awt\image, or java:awt:image on the UNIX, Windows, or Macintosh file system, respectively. The package name must be chosen carefully. The package cannot be renamed without renaming the directory in which the classes are stored. Finding Packages and CLASSPATH For example, consider the following package specification. package MyPack; In order for a program to find MyPack, one of two things must be true. Either the A Short Package Example package MyPack; System.out.println(name + ": $" + bal); java MyPack.AccountBalance Importing Packages Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name. The import statement is a convenience to the programmer and is not technically needed to write a complete Java program. If you are going to refer to a few dozen classes in your application, however, the import statement will save a lot of typing. In a Java source file, import statements occur immediately following the package import pkg1[.pkg2].(classname|*);
TestBalance imports MyPack and is then able to make use of the Balance class: import MyPack.*; |