Monday, January 14, 2013

What is the use of static import?


The use of static import in Java is quite simple: to provide the convenience to Java programmers when they use some fields or methods from a static class.
For example in your codes you want to use abs(int ) from static class Math.   Normally your codes will be like:

double d1 = Math.abs(-0.29);
double d2 = Math.abs(-0.39);


With using static import you don't need to specify Math class you can directly use abs(int) method.


import static java.lang.Math.*;
double d1 = abs(-0.29);
double d2 = abs(-0.29);

You can see that: you could save some time when you have many places to use abs(int) method in your Java codes since you don't need to type in Math for each invocation.

But in my opinion if in you Java file you have multiple static classes you should be cautious with using static import.   It may reduce the readability of your Java codes.  Any new comer who reads your codes first time may want to know which staic class a particular method belongs to and he may find it a bit harder to do so becuase of static import. 

No comments:

Post a Comment