Java Package Imports
Importing Packages with the import Statement
import pname.clazz;
import pname.*;
pname: package name
clazz: class name
A class name that includes the package is called an FQN, or fully qualified name. Originally, to declare a class, it must be written with the FQN. However, writing a name such as com.devkuma.tutorial.basic.Animal every time is cumbersome.
For that reason, you can declare the package to use in advance with import, allowing code to be written without the package name. The import statement is generally written immediately after the package declaration. For example, the following is equivalent.
package com.devkuma.basic.imports;
import com.devkuma.tutorial.basic.Animal;
// ... omitted ...
Animal a = new Animal();
Without an import declaration, it must be written as follows.
com.devkuma.tutorial.basic.Animal a = new com.devkuma.tutorial.basic.Animal();
If you want to import all classes under the com.devkuma.tutorial.basic package together, you can write it as follows.
import com.devkuma.tutorial.basic.*;
An import declaration only means declaring a name, so using * does not import the entire package and make the app larger. However, these days it is customary to avoid * (on-demand import) as much as possible in order to make the classes used in the code clear.
import static Statement - Importing Class Methods and Fields
import static pname.clazz.member;
import static pname.clazz.*;
pname: package name
clazz: class name
member: member name
Using the import static statement, you can call class members without specifying the class name.
For example, the following gets an absolute value using the abs method of the java.lang.Math class. When calling it, you do not need to write something like Math.~.
package com.devkuma.basic.imports;
import static java.lang.Math.*;
public class ClassStaticImport {
public static void main(String[] args) {
System.out.println(abs(-10)); // Result: 10
}
}
As with ordinary class imports, it is also possible to specify the member name. In the case above, calling the import static statement as follows has the same meaning.
import static java.lang.Math.abs