Good day!

I have such a question on java. Usually looking at someone else's code, I see that not all the packages are imported, but only specific types of them. Why not import the entire package, so as not to write a bunch of imports, one for each desired type? What is worse?

    2 answers 2

    The main reason is to avoid class name conflicts.

    Suppose you have an abc package with classes A , B and C And the xyz package with classes M , N and ... C

    Suppose we import classes B and N We can import them correctly:

     import abcB; import xyzN; 

    but we can be lazy and write:

     import abc*; import xyz*; 

    In the first case, everything will be fine. And in the second there will be a conflict of names between the classes abcC and xyzC . Since there are many quite generic class names (especially interfaces, such as some Event , Listener , Command , etc.), it is worthwhile to import them explicitly in order to avoid conflict.

    • one
      Plus the general import uncertainty. There is a class, and where it comes from - you will not understand. Or vice versa, you wonder what came from import. Imports, as an introductory section of a class, must clearly form the scope of the class so that any developer can see the specific imports. - etki
    1. Memory will eat more
    2. Modern ideas automatically write imports (idea at least for sure). And what's the difference for writing an import for each class, or import a whole package? (the main reason)
    • > Memory will eat more. Modern compilers are probably smart enough to actually import only the types used in the code. > And what difference does it make for ideals to write import for each class, or import a whole package? One import of the whole package will look like one line, and one hundred imports for each type will be one hundred lines. - JuniorTwo
    • one
      > (main reason) Nope ... - Nofate