Static imports have been around since Java 1.5, but they are a feature that I have rarely used, or even seen much in code. I guess that's because static imports is not a must have thing, but something that is nice to have. Using static imports takes some pain away from typing code.
For example, instead of writing
System.out.println("some message");
we could statically import System.out and write it as follows:
static import System.out; public class HelloWorld { public static void main(String args[]) { out.println("Hello World"); } } |
Well using static imports definetely takes the pain away from typing System.out every time. However sometimes using static imports can also reduce the readability of code, because we would have to look at the imports to know if a variable in code was declared within that class itself or imported statically.
Having said that, one place where I would definetely use static imports is in importing enums. Since elements of an enum are always public static final, it makes some sense to statically import all the enum elements so that we do not have to qualify them while using them.
|
|
Resource:
Comments