Packages in Java with example program

Packages in Java:

The package is a way of grouping a variety of classes and interfaces. The grouping is usually done according to functionality. Packages act as “Containers” for classes.

Special Characteristics of Packages:

1. The classes contained in the packages of other programs can be easily reused.

2. In packages, classes can be unique compared with classes in other packages which means two classes in two different packages can have the same name. They may be referred to by their fully qualified name, comprising the package name and the class name.

3. Packages provide a way to hide classes thus preventing other programs or packages from accessing classes that are meant for internal use only.

4. Packages also provide a way for separating “design” from coding. At first, we can design classes and decide their relationships and then we can implement the Java code needed for the methods.

System Package:

In many situations, we might want to use a class in several places in the program or we may like to use many of the classes contained in a package. it has the following syntax:

import package-name.class-name;


import package-name.*;


import.pack.Test; // Test is the class-name

Example :


Creating package:

Creating the package involves the following steps:
1. Declare the package at the beginning of a file using the :

package package-name;

2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing of the class-name .java file in the subdirectory created.
5. Compile the file, and create a .class file in the subdirectory

Static import:

It is a feature that eliminates the need for qualifying a static member with the class name. The static import declaration is similar to that of import. We can use the static import statement to import static members from classes and use them without qualifying the class name. It has the following syntax:

import static package-name.subpackage-name.class-name.staticmember-name;


import static package-name.subpackage-name.class-name.*;