Monday, December 04, 2006

Static Import

Today when i was going through the installation and usage of Watij(Web Application Testing In Java) a tool for web testing in java. I came across usage of static import in java.
In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:
double r =
Math.cos(Math.PI * theta);
In order to remove the code for acessing every static variable by the class name we can have a static import similar to any other import
import static java.lang.Math.PI;
and then use the variable PI like any other variable
double r =
Math.cos(PI * theta);
If we use then the above statement can be rewritten as below
import static java.lang.Math.*;
double r = cos(PI * theta);
using static imports has its pros and cons
One advantage is that if the developer is using PI at many places in the code then he need not do a reference with the class name every time he can use it as a class level static variable.
But this is also a disadvantage as the code may become confusing if there is no reference of PI anywhere in the program and any other guy who sees this code may get confused as to where is the variable declared.
For more info on this can Click here



1 Comments:

At 9:36 AM , Blogger Parag said...

B.M.
That was an interesting post. Not many people know about static imports. One of the reasons it is not used is, if we statically import a class, then we need to write only the method name for the invocation. This can be misunderstood to be a local method by someone who is reading the program. Offcourse an IDE (as well as the import statement) will tell him that it is a static method in an imported class, but then again, if we are using IDE's, then we can customize them with shortcuts to autogenerate commonly used method names.
However it's nice to read about such (commonly unknown) features. Who knows, we might actually have to encounter such esoteric code sometime :-)

--
Regards
Parag

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home