Forms of static imports
Static Imports in java comes in two forms:
- Import a particular static member of a class.
import static packageName.className.staticMemberName;
for ex. java.lang.System.out; - Import all static members of a class.
import static packageName.className.*;
for ex. java.lang.Integer.*;
Let’s look at the static imports with a simple example:
Without using static imports
public class WithoutStaticImportProg {
public static void main(String[] pmt) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}
Using static imports
import static java.lang.System.out;
import static java.lang.Integer.*;
public class StaticImportProg {
public static void main(String[] pmt) {
out.println(MAX_VALUE);
out.println(toHexString(42));
}
}
Both classes produce the same output:
2147483647
2a
Points to remember for static imports:
- If you use static import for MAX_VALUE member for both Integer and Long class in the same program, you will get a compilation error, since both have a MAX_VALUE constant. Java won’t come to know which class MAX_VALUE you are talking about.
- Static imports can only be used with static object references, constants (as they are static and final), and static methods.
- You can use import static; you can’t say static import.
No comments:
Post a Comment