Java Static Import Explained With Easy Example With Source Code

What is Static Import?

Static Import is a feature in Java that allows you to access the methods and variables that are defined as public static to be used in a class without having to use the class name.

Let’s say there is a following class with a static field and a static method.

package com.sample;
public Class MyClassOne() {
	public static int a_number = 3;
	
	public static void doSomething(int number) {
		System.out.println("Did Something " + number);
	}
}


Now let’s create another class that use variable and method from this class. I am not suggesting you should make your variable public – this is for demonstration purpose only. A good programming practice is to declare your variables private and expose them via getters and setters method as necessary.

Regular Way (Non Static Import)

package com.sampletwo;

import com.sample.MyClassOne;

public Class MyClassTwo() {
	
	
	public static void doSomethingTwo() {
		MyClassOne.doSoemthing(MyClassOne.a_number);
	}
}


With Static Import, the code becomes

package com.sampletwo;

import com.sample.MyClassOne.*;

public Class MyClassTwoStatic() {
	
	
	public static void doSomethingTwo() {
		doSomething(a_number);
	}
}


Note: Do not statically import methods with a name that is identical to a method in Object, because methods that are naturally in scope take precedence over static imports