Consider the following class
public final class Constant { public static final String USER_NAME="user1"; //more constant here }
This class in the package B.
Now I am going to use this in package A. Consider following two ways which can use.
Method 1- use import B.Constant
import B.Constant; public class ValidateUser { public static void main(String[] args) { if(Constant.USER_NAME.equals("user1")){ } } }
Method 2- use import static B.Constant.USER_NAME;
import static B.Constant.USER_NAME; public class ValidateUser { public static void main(String[] args) { if(USER_NAME.equals("user1")){ } } }
My question is is there any difference or advantage normal import over static import in this case?
Difference between import and static import: With the help of import, we are able to access classes and interfaces which are present in any package. But using static import, we can access all the static members (variables and methods) of a class directly without explicitly calling class name.
import static is used to import static members of a class, you can import a specific member of class or import en masse. Used sparingly and in case of importing static members of one or two classes, static import in Java can increase readability of a program by removing the boilerplate of repetition of class names.
by Joshua Bloch.) This is considered bad Java programming practice because when a class implements an interface, it becomes part of the class's public API. Implementation details, such as using the static members of another class, should not leak into public APIs.
Advantages: Import statements help in reducing the code size and hence save a lot of time. It improves the readability of our code. It is pretty useful while handling big projects.
The only difference between a normal import
and an import static
is that the latter is for moving static
members of some other class or interface — especially constants — into scope. It's up to you whether you use it; I like it because it keeps the body of the class shorter, but YMMV.
There are no performance benefits or penalties to using them (except possibly when compiling, as if you care about that) as they compile into identical bytecode.
The main difference is Readablity, Constant.USER_NAME
is less readable when compared to USER_NAME
.
From Documentation:
Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names.
But in any case, try to avoid doing
import static B.Constant.*;
because it can pollute its namespace with all the static members you import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With