Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the advantage to use "import static"? [duplicate]

Tags:

java

What's the good point to use "import static"?

like image 898
user496949 Avatar asked Mar 04 '11 06:03

user496949


People also ask

What is the benefit of static import?

Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names. The important points to note here: Use it when you require frequent access to static members from one or two classes. Used appropriately, static import can make your program more readable.

Why are static imports bad Java?

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.

What is the difference between static import and import?

What is the difference between import and static import? The import allows the java programmer to access classes of a package without package qualification whereas the static import feature allows to access the static members of a class without the class qualification.

What a static import is and what the pitfalls of using this are?

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.


2 Answers

In general you should use static imports very sparingly.

One of the few places that they make a lot of sense is in your unit tests:

import static junit.framework.Assert.*;

Static imports were added to Java to stop programmers from implementing the Constant Interface Antipattern.

like image 155
dbyrne Avatar answered Nov 15 '22 12:11

dbyrne


It allows you to remove the class name from function calls for static methods, as described with examples in the documentation here: http://download.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

like image 37
Will Avatar answered Nov 15 '22 13:11

Will