Monday, November 3, 2008

Static Imports in Java

Java as a language, continues to evolve and amaze developers and students alike with new innovative concepts and features. Java 5 is a major release which includes various additions like Generics, Autoboxing, Enumerations, Enhanced for-loop, Static Imports, Var-args, Serialization, Covariant return types, Annotations etc. to name a few.

Discussing each one of them would span multiple blog entries. So let's start with Static Imports as of now. Hopefully, I will devote an entry to each one of these in the coming days. :-)

Before I begin with my explanation of Static Imports, I would like to ask you something..........
Are you sick and tired of using fully-qualified static members of some other class (can be a library class too) in your program such as Math.PI whenever you want to use 3.141592653589793.... or Math.sqrt() when you need to find out square root of any number ??

Of course, these are simple examples which are short and easy to remember, so they might not seem a headache. But things can get quite complex and it can turn out to be burdensome to repeat a long fully-qualified name time and again in your code. 
Static Imports come to your rescue. :-)

With the help of Static imports, you can very well use the static members of any other class (to which you have access) like the members of your class i.e. there is no need to fully qualify the name using package name and class name 

Normally an import statement would look like 
import packageName.className.memberName;

A static import would just add the word "static" after import 
import static packageName.className.memberName;

An example would make it more clear....

>  import static java.lang.Math.*;
>  public class tryme
>  {
>    public static void main(String[] args)
>    {
>      System.out.println("Square root of PI is "+sqrt(PI));
>    }
>  }

The advantage lies in the fact that you dont have to type Math.PI....a simple PI would work....
I agree that its a small feature and not as important as other features that Java 5 has introduced or enhanced, but then as they say "Boond boond se hi gaadha badhta hain"

Limitations :
It applies to only static members, not to instance variables 
It can make code un-readable and difficult to debug, if used unnecessarily and in excess

Application:
Mostly it is used to discourage the technique of declaring constants in interfaces and then implementing those interfaces by your class. An interface is a part of public API and it defines services that your class should provide, and so it is not recommended to make constants a part of your public API. Instead, it is always preferable to use Static Imports.

No comments: