How to use static import in Java

Using static import in Java, a fantastic feature
static import is one of the fantastic feature of the Java programming language. It enables you to import the static members of a class, thereby giving you a chance to access them directly without the classname. For example, to access sqrt() (static) method in Math class, you would write Math.sqrt(). Using import static, you can directly call, sqrt().

import static <ClassName>.<StaticMember>;
import static <ClassName>.*; (for all static members)
Here <ClassName> corresponds to full class path.

This statement lets you import static members of the class. The disadvantage of static import is that, when you import static members of multiple classes and use them in your code, you might be later confused of where you got a method from since there is no class name specified before it. But if you would like to use it for one or two, that is OK. However, this an also be advantage as it reduces the amount of code written. Java organizes its libraries into packages to avoid the pollution of namespace, but excessive static import pollutes it since all the static members you import occupy your program's namespace. So, don't use it when you use the static members a few times. Here is an example.

import static java.lang.System.*;
import static java.lang.Math.*;
class StaticImportDemo
{
    public static void main(String args[])
    {
        out.println("In println() "+PI);
    }
}

The above example, is obviously a bad practice. Because, we are importing every static member of both the classes and have used only two of them. So, a good practice of the above code would be replacing the first two statements as below.


import static java.lang.System.out;
import static java.lang.Math.PI;

Don't forget the above, line, first of all the above program isn't also a good way to use the static import because we have used those static members (out and PI) only once.


Posted by at on

Tags: Keywords,