Using * in an import statement in Java

Can someone explain to me import operations in Java. Some imports have a * suffix, and some do not. What is the difference between the two? Does using * in import use all classes?

see import here

Here they said that while import statements seem nested, it is not. Can someone explain in detail?

0
source share
4 answers

Use * is considered bad practice. It is used to import all files inside this package. A better way to do this is to list each of the classes that you need, especially in a scenario where you are viewing code outside of the IDE, and you need to know which version of the class you are using. Essentially, it creates laziness in the development team.

A comment

For those who claim that this is not a “bad” practice, as I said. How can you say this is good practice?

 import java.util.*; import java.io.*; 

Even if the compiler ignores everything under * except the imported List , how can this help someone to look at the code in the future? I think many people forget that you are writing code for people, not for computers. How could you convert this code when Java leaves and you use SuperAwesomeLanguage? In the following example, please convert this to a new language when you have a ZERO knowledge of java:

 public class Foo { private List list; } 

Is List in io ? io required? The problem is that you do not know. Therefore, being explicit, you can guide future developers as to which classes are needed.

+4
source

Does using * in the import statement use all classes

Yes.

From the Oracle documentation:

The declaration of type-import-on-demand allows all available types to have a named package or a type that must be imported as needed.

+1
source

From your link:

import java.util. *;

* is a regular expression operator that will match any combination of characters. Therefore, this import statement will import everything into java.util. If you tried to log in and run the sample program above, you can change the import statement to this one.

So yes * the suffix imports all classes in this path

+1
source
 import com.example.* 

Imports all classes into com.example package

 import com.example.ClassName 

Imports only the ClassName class

+1
source

Source: https://habr.com/ru/post/1209931/


All Articles