Showing posts with label Packages. Show all posts
Showing posts with label Packages. Show all posts

Monday, July 5, 2010

Packages Basics

Packages are containers for classes that are used to keep the class namespace partitioned. The package is both a naming and a visibility control mechanism. We can control the visibility of classes within a package using the various access specifiers.

Defining a Package

To define a package the package command is included as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored.

package pakage_name;

/* If you omit the package statement, the class names are put into the default package, which has no name.*/

Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage.

Package Hierarchy

To create a hierarchy of packages, separate each package name from the one above it by use of a period.


package pkg1[.pkg2[.pkg3]];

/* A package hierarchy must be reflected in the file system of your Java development system. */

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.


In a Java source file, import statements occur immediately following the package statement (if it exists) and before any class definitions. This is the general form of the import statement:
import pkg1[.pkg2].(classname | *);

/* the star form may increase compilation time—especially if you import several large packages.For this reason it is a good idea to explicitly name the classes that you want to use rather than importing whole packages. However, the star form has absolutely no effect on the run-time performance or size of your classes.*/