Java Packages


Packages are named groups of related classes. In java the classes can be grouped together in packages. We can specify the package name using a package declaration:

package name ;

The package declaration must be the first (non-comment) line in the .java file. If a file contains a package declaration as above, the file must be in a subdirectory called name i.e. the directory name must match the package name.

We can access public classes in another (named) package using:

package-name.class-name

We can access the public fields and methods of such classes as under:

package-name.class-name.field-or-method-name

We can avoid having to include the package-name using import package-name.* orimport package-name.class-name at the beginning of the file after the package declaration, if any. The former imports all of the classes in the package, and the later imports just the named class. We can have as many import statements as we need. We must still use the class-name to access the classes in the package, and class-name.field-or-method-name to access the fields and methods of the class; the only thing you can leave off is the package name.