Introduction to Java Packages

In this post, you will learn to:

  • Identify the features of packages and their types.
  • State the steps for creating and using user-defined packages.
  • Explain static imports

A Java package is a group of related classes and interfaces organized as one unit. The fully qualified name of the class includes the package it belongs to. For instance, tools.drawing.Shapes is the fully-qualified name of the class Shape.

A Java package has the following:

Features

Features of Java packages are as follows:

  • A package can have sub packages.
  • A package cannot have two members with the same name.
  • If a class or interface is bundled inside a package, it must be referenced using its fully qualified name, which is the name of the Java class including its package name.
  • If multiple classes and interfaces are defined in a single Java source file within a package, then only one of them can be public.
  • Package names are written in lowercase.
  • Standard packages in the Java language begin with java or javax.

Types

The Java API library consists of a vast set of packages. Classes and interfaces are bundled by the function and purpose they serve. By default, every Java application or applet has access to the core package in the API, the java.lang package.

Types of Java packages are as follows:

  • Predefined packages
  • User-defined packages

Predefined packages are part of the Java API. User–defined packages are created by the developers. Predefined packages that are commonly used are as follows:

java.io
java.util
java.awt
Note: Consider a cabinet drawer holding a set of related files and folders. If all files and folders were lumped together in one location, it would lead to an unorganized mess and chaos. This would cause waste of time while searching for a particular file. Organizing the files into relevant drawers helps to maintain orderliness and improve efficiency. A package in Java has the same concept.

User-Defined Packages

Java allows the user to import the classes from user-defined packages using an import statement.

import firm.Employee;   //Imports the Employee class from the package firm
import firm.*;    //Imports all classes from package firm

The steps to create a Java package have been described one by one.

Step 1: Select a name for the package.

While deciding a name for the package, naming conventions rules has to be followed and they are as follows:

  • Package names should be written in lowercase. Package names should not begin with java or javax, because they are used for packages that are part of the Java API.
  • Package names cannot begin with a digit and have hyphens, they can however have an underscore.

Step 2:Create a folder with the same name as the package.

The naming structure for a package is hierarchical, so programs containing classes and interfaces should be placed under a folder of the same name as the package.

Step 3: Place the source files in the folder created for the package.

Add the package statement as the first line in all the source files under that package. There can only be one package statement in a source file. The following is the syntax to add the package statement in the source file.

Syntax:

package <packagename>;

Step 4: Compile and Execute the application.

While executing, make sure to use the fully qualified name of the class, that is, the name of the class including its package name. The following code demonstrates how to add a package statement in the Java source file.

Code Snippet:

package firm;

public class Employee {

int empId;
String empName;
String address;

public Employee()
{
    System.out.println("Constructor of Employee");
}

public static void main(String args[])
{
   Employee e=new Employee();
}
}

Save the source file as Employee.java in a folder named firm. Compile the code as follows:

javac Employee.java

Or, compile the source file with –d option as follows:

javac –d . Employee.java

Where –d option stands for directory and . stands for current directory. The command will create a sub folder named firm and place the compiled class file inside it. From the parent folder of the source file, execute the code with its fully qualified name:

java firm.Employee

To make use of the class elsewhere, the import statement is used. One example of using import statement, to import Employee class from the package firm is shown in the following statement:

import firm.Employee;   //imports a single class

The following code demonstrates how to use the class, Employee from the package firm in another class Resources which is in a different package.

Code Snippet:

package company;
import firm.Employee;
public class Resources {
    public void testMethod() {
       Employee objEmployee = new Employee();
    }
}

To indicate that class Resources belongs to package company, the package statement is added as the first line of the code. To use the class Employee in the class Resources, it needs to be imported with the import statement. At the time of compiling the class Resources, it is mandatory to ensure that the classpath includes the directory in which the other package (in this case, firm) is present.

All import statements in a class must be placed after the package statement and before the class declaration. The import and package statements placed in a file affect all the classes in a file and cannot be applied selectively to particular classes in a file.

In the package statement, names of packages and subpackages are separated by periods. Each component of the package name must be a directory name on the local machine. For example, if the package statement is as follows:

package demo.management.list.src;

Then, there must be directories created in the following hierarchy:

demo\management\list\src.

Static Imports

Normally, to access static members of a class within another class, it is required to use fully qualified name of the static member. This can however be relatively cumbersome, especially when many static members are used in a single statement. Java provides a workaround for this situation through static imports. The static import statement allows static members to be used without qualifying them with the class name and without inheriting from the type that contains the static members. static imports allow a program to import static members either individually or as a whole.

For example, if the class Machines belonging to package mnc.factory has a static member boltSize which needs to be used in the class Gadgets, then a static import statement for it can be written.Once this is done, boltSize can be used anywhere inside Gadgets without using a qualifying name.

The following code demonstrates the use of static imports statement.

Code Snippet:

import static mnc.factory.Machines.boltSize;
class Gadgets {
    public void assign() {
        boltSize = 20; 
    }
}

Static imports can also be used with built-in libraries, such as:

import static java.lang.Math.PI; 
double area = PI*radius*radius;    // Using static const PI

Though static imports is a useful feature, it should not be used too frequently. Using too many static imports in a program can hamper readability and also cause maintenance problems.

Related Post