Saturday, September 18, 2021

Static Import Statements

     The import statement was enhanced to provide even greater keystroke-reduction capabilities, although some would argue that this comes at the expense of readability. This feature is known as static imports. Static imports can be used when you want to "save typing" while using a class's static members.

Before static imports:
public class TestStatic {
public static void main(String[] args) {
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.toHexString(42));
}
}

After static imports:
import static java.lang.System.out; // 1
import static java.lang.Integer.*; // 2
public class TestStaticImport {
public static void main(String[] args) {
out.println(MAX_VALUE); // 3
out.println(toHexString(42)); // 4
}
}
Both classes produce the same output:
2147483647
2a

static import feature:

1. Even though the feature is commonly called "static import" the syntax
MUST be import static followed by the fully qualified name of the
static member you want to import, or a wildcard. In this case, we're doing
a static import on the System class out object.

2. In this case we might want to use several of the static members of the
java.lang.Integer class. This static import statement uses the wildcard to
say, "I want to do static imports of ALL the static members in this class."

3. Now we're finally seeing the benefit of the static import feature! We didn't
have to type the System in System.out.println! Wow! Second, we didn't
have to type the Integer in Integer.MAX_VALUE. So in this line of code we
were able to use a shortcut for a static method AND a constant.

4. Finally, we do one more shortcut, this time for a method in the Integer class.

Here are a couple of rules for using static imports:

You must say import static; you can't say static import.

Watch out for ambiguously named static members. For instance, if you do a
static import for both the Integer class and the Long class, referring to MAX_
VALUE will cause a compiler error, since both Integer and Long have a MAX_
VALUE constant, and Java won't know which MAX_VALUE you're referring to.

You can do a static import on static object references, constants (remember
they're static and final), and static methods.


No comments:

Post a Comment

Variable Declarations

  There are two types of variables in Java: ■ Primitives A primitive can be one of eight types: char , boolean , byte , short , int , long...