How to import Java packages

Description

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

Syntax

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.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures