Defining Packages
A package hierarchy represents an organization of the Java classes and interfaces. It does not represent the source code organization of the classes and interfaces. The source code is of no consequence in this regard. Each Java source file (also called compilation unit) can contain zero or more type declarations, but the compiler produces a separate class file containing the Java bytecode for each of them. A type declaration can indicate that its Java bytecode should be placed in a particular package, using a package declaration.
The package statement has the following syntax:
package
fully_qualified_package_name
;
At most, one package declaration can appear in a source file, and it must be the first statement in the source file. The package name is saved in the Java bytecode of the types contained in the package. Java naming conventions recommend writing package names in lowercase letters.
Note that this scheme has two consequences. First, all the classes and interfaces in a source file will be placed in the same package. Second, several source files can be used to specify the contents of a package.
If a package declaration is omitted in a compilation unit, the Java bytecode for the declarations in the compilation unit will belong to an unnamed package (also called the default package), which is typically synonymous with the current working directory on the host system.
Example 6.1 illustrates how the packages in Figure 6.2 can be defined using the package declaration. There are four compilation units. Each compilation unit has a package declaration, ensuring that the type declarations are compiled into the correct package. The complete code can be found in Example 6.7, p. 345.
Example 6.1 Defining Packages and Using Type Import
// File name: Clown.java // This file has 2 type declarations
package wizard.pandorasbox; // Package declaration
import wizard.pandorasbox.artifacts.Ailment; // Importing specific class
public class Clown implements Magic { /* … */ }
interface Magic { /* … */ }
// File name: LovePotion.java
package wizard.pandorasbox; // Package declaration
public class LovePotion { /* … */ }
// File name: Ailment.java
package wizard.pandorasbox.artifacts; // Package declaration
public class Ailment { /* … */ }
// File name: Baldness.java // This file has 2 type declarations
package wizard.spells; // Package declaration
import wizard.pandorasbox.*; // (1) Type-import-on-demand
import wizard.pandorasbox.artifacts.*; // (2) Import from subpackage
public class Baldness extends Ailment { // Simple name for Ailment
wizard.pandorasbox.LovePotion tlcOne; // (3) Fully qualified class name
LovePotion tlcTwo; // Class in same package
// …
}
class LovePotion { /* … */ }