The Java Spec: Packages

The Java Language Specification

## 6 Packages

Packages are groups of classes and interfaces. They are a tool for managing a large namespace and avoiding conflicts. Every class and interface name is contained in some package. By convention, package names consist of period-separated words, with the first name representing the organization that developed the package.

### 6.1 Specifying a Compilation Unit's Package

The package that a compilation unit is in is specified by a package statement. When this statement is present, it must be the first non-comment, non-white space line in the compilation unit. It has the following format:

    	package packageName;

When a compilation unit has no package statement, the unit is placed in a default package, which has no name.

### 6.2 Using Classes and Interfaces from Other Packages

The language provides a mechanism for making the definitions and implementations of classes and interfaces available across packages. The import keyword is used to mark classes as being imported into the current package. A compilation unit automatically imports every class and interface in its own package.

Code in one package can specify classes or interfaces from another package in one of two ways:

- By prefacing each reference to the class or interface name with the name of its package:

             // prefacing with a package
             acme.project.FooBar obj = new acme.project.FooBar();

- By importing the class or interface or the package that contains it, using an import statement. Importing a class or interface makes the name of the class or interface available in the current namespace. Importing a package makes the names of all of its public classes and interfaces available. The construct:

      	// import all classes from acme.project
      	import acme.project.*;

  means that every public class from acme.project is imported.

The following construct imports a single class, Employee_List, from the acme.project package:

             // import Employee_List from acme.project
             import acme.project.Employee_List;
             Employee_List obj = new Employee_List();

It is illegal to specify an ambiguous class name and doing so always generates a compile-time error. Class names may be disambiguated through the use of a fully qualified class name, i.e., one that includes the name of the class's package.

The Java Language Specification