What is static import ?

Sometimes we can use static imports instead of normal imports in Java. We can do that, for example, for JUnit assertions as assertTrue or assertFalse. We can also use it for some of java.lang.Math components (PI, E).

Static import allows an access only for static members of given class. In additionnaly, it doesn't provoke to inherite the type of these members. Members are imported individually. That means that in following case, we don't have a name conflict between java.lang.Math object and our test.Math ones because we use only static members of the first one:

// Math.java
public class Math {

	public void printTest() {
		System.out.println("Test from customized Math class");

// StaticImportTest.java
public class StaticImportTest {

	public void test() {
		System.out.println("PI is :"+PI);
		Math m = new Math();

// printed result should be:
// PI is :3.141592653589793
// Test from customized Math class

As you can see in our example, imported static members can be used without qualification (we use simple PI instead of Math.PI). However, don't abuse with static imports because the code can quickly become hard to read and to maintain. Also, it's more difficult to guess that, in our case, PI comes from java.lang.Math and not from another class which could be used.