Package in Java: How to create, store, packages?

The concept of package is to create a container for classes. It is done to avoid class collisions. The name of class inside a package is for that particular package and it has nothing to do with other classes outside the package. Creating packages are helpful when you are dealing with many classes. This way it is easier to access a particular class and also there will not be a problem for dealing with duplicate class names. Packages use the concept of encapsulation in Java.

To create a package in Java, package keyword is used:

package name_of_package;

Now, any class which is declared in this package will belong to this package.

For Example:

package TestPackage;

Packages are stored in file system directories and the directory name should be same as that of package name. So TestPackage will be stored in a directory named TestPackage. Also, one package can be used in many files.

Packages are stored in a hierarchical fashion:

package package1[.package2[.package3]];

For Example:

package java.awt.color;

is stored as java/awt/color in UNIX

is stored as java\awt\color in Windows/PC

is stored as java:awt:color in Mac

When a package is created, Java run time system could find it by either of two ways: by looking for the current directory or by setting the CLASSPATH variable.

Leave a Reply