Tuesday, December 29, 2009

Packages in JAVA

Packages are used, to allow re-use of names. A package consists of classes and interfaces. It is a grouping of related types providing access protection and name space management. Common reasons to bundle classes and interfaces in a single package are:
  • Everyone can easily determine that these types are related
  • Locating types that can provide a specific functionality is easy
  • Names can re-used. That is, a single package is a single namespace.
  • Access priviledges can be set for complete access within the package but zero access outside the package.

Java platform comes with innumerable number of packages. The most fundamental among them are java.lang and java.io.

Creating a Package

This is as simple as choosing a naming as per the convention and putting this name along with the package statement in every source-file that is included in the package. The package statement looks like this:
package networking;
In the above statement 'networking' is the name of the package. The package statement should always be the first statement in a source-file followed by class definitions.

Naming Conventions

In package names all letters are in lower-case. Packages the come with JAVA platform begin with either java or javax. Packages created by outside companies generally use their domain names in reverse order as a prefix. For example, com.company.package is the fully-qualified name of a package created by a company whose webaddress is www.company.com

Accessing Package Members

Public members inside a package can be accessed by any of the following methods:
  • Refer to the member by its fully qualified name
  • Import the package member
  • Import the member's entire package

Miscellaneous

  1. Most of the package-names look as if there are in some hierarchy, but in fact all are nothing but different packages. For example, java.awt is a package of its own while java.awt.color and java.awt.font are different packages of there own.
  2. If the two packages, having similar classnames for two or more classes are imported, then the qualified name of the class should be used.
  3. Static Import statement can be used to avoid prefixing the static member calls with the classnames.


tutorials

No comments:

Post a Comment