Java Packages Import

In this chapter you will learn:

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

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.

Next chapter...

What you will learn in the next chapter:

  1. What is a Java Interface
  2. How to define an interface
  3. Note for Java Interface
  4. How to implement an interface