Talking about import command in Java, we may ask the following questions:
What does the import command in Java do?
The import command in Java makes us possible to use the name of other classes in our class without having to explicitly declare the name of the package containing that class.
In the example above, the Example class and the Student class are in two different packages. When the Example class uses the Student class, without having to declare the package name we use import com.huongdanjava.Student.
Can we not use the import command?
Of course, we can, don’t use the import command, then we must declare the package name of the Student class as follows:
The import command does not embed the contents of other classes into our class, so it will not increase the size of our class files. It only helps us, just declare the class name in another package and then we can use that class.
For the class of the same name can use the import command or not?
In the case where we use two classes with the same name in two different packages, we do not use the import statement with them. Now we have to declare the package name for each class.
Here, I use two classes with the same name Student, one in the package com.huongdanjava, the remaining package is com.huongdanjava.oca. I have to declare the package name for both classes, I can not declare them as follows:
However, you can also use the import statement for a class, while the remaining classes require you to declare the package name.
In this example, the Student class in the com.huongdanjava package uses the import statement, so when you use it you do not need to declare the package name anymore. The class Student in the package com.huongdanjava.oca is required to declare the package name.
Is there a way to use an import statement for multiple classes in the same package?
If we use multiple classes in the same package, we can use an import statement for all of the following:
In this example, the Student class and the School class are in the same package as com.huongdanjava. To use these two classes we can declare all classes in this package import com.huongdanjava. *;
Static import statement
If we want to use static variables or static methods of other classes in our class, we can use the import static statement.
Here I define the Student class a static NAME variable and a static method goToSchool() as follows:
To use these variables and methods without declaring the package name and class name, we can declare the following in the Example class:
In addition, we cannot swap the position of the two import and static words in the import static statement.