Import Packages

In this chapter you will learn:

  1. How to write import statement
  2. What is static import and how to use static import

import statement syntax

In a Java source file, import statements occur immediately following the package statement and before class definitions.

This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

* means including all classes under that package. For example,

import java.lang.*;

Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy.

For example, this fragment uses an import statement:

import java.util.*; 
class MyDate extends Date { 
}

The same example without the import statement looks like this:

class MyDate extends java.util.Date { 
}

static import

In order to access static members, it is necessary to qualify references. For example, one must say:

double r = Math.cos(Math.PI * theta);

The static import construct allows unqualified access to static members.

import static java.lang.Math.PI;

or:

import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:

double r = cos(PI * theta);

The static import declaration imports static members from classes, allowing them to be used without class qualification.

Next chapter...

What you will learn in the next chapter:

  1. How is Java source file organized