Wednesday, August 14, 2013

What is the use of Static Import?

Static Import is a new feature added in Java 5 specification.

let's first know, why do we use "import".
If we write as mentioned below

import form.ArtworkForm;

It gives access to use class 'ArtworkForm' inside whole program without using package reference.
'form' is a name of package here.

We can create any object of this class..
ArtworkForm obj=new ArtworkForm();

If we use * after package name in import statement, then it will give you access to use all classes
and it's method or members.

import form.*;

Now let's get into details with "Static import"...

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

In the above line, we are using Math.cos and Math.PI. somewhere it looks awkward, to make it looks good
we can use as mentioned below.

import static java.lang.Math.PI;
import static java.lang.Math.cos;

now the code would be like this...

double r = cos(PI * theta); (It seems good)

Only advantage that I see is readability of the code. Instead of writing name of static class,
one can directly write the method or member variable name.