Java Package

In this chapter you will learn:

  1. What is Java package
  2. How to define a Java package
  3. How to create a hierarchy of packages
  4. How to map Java package to directory

Description

Packages are containers for classes. Packages are used to keep the class name space compartmentalized. In Java, package is mapped to a folder on your hard drive.

Syntax

To define a package, include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package.

If you omit the package statement, the class names are put into the default package, which has no name.This is the general form of the package statement:


package packageName;

Create a hierarchy of packages

To create a hierarchy of packages, separate each package name from the one above it by use of a period. The general form of a multileveled package statement:


package pkg1[.pkg2[.pkg3]];

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

Java package maps to directory

Java package maps to physical directory on your hard drive. As what is defined in the following example, you have to save the following file to a file named Main.java and create a folder named MyPack to actually store Main.java file.


package MyPack;//from w w  w.  j av  a  2  s  .c o  m

public class Main {
  public static void main(String args[]) {
    System.out.println("hi");
  }
}

Then try executing the class, using the following command line:

Next chapter...

What you will learn in the next chapter:

  1. How to write import statement
  2. Syntax for Java Packages Import
  3. What is static import and how to use static import