Java import confusion

前端 未结 4 662
半阙折子戏
半阙折子戏 2020-12-18 23:08

What is the difference between:

java.awt.*;

and:

java.awt.event.*;

I find both in many programs.

4条回答
  •  星月不相逢
    2020-12-18 23:28

    The first only imports types from the java.awt package (but not its subpackages), and the other imports only from java.awt.event (but not from any other packages).

    While packages in Java can (and should be) organized in a hierarchy, the import statement tends to be "conservative" - when you import all the types from within that package, you get only those specifically at that level, not at lower level in the hierarchy.

    I think that the rationale behind it is to avoid spurious imports. It is generally a good idea to import as little as you can - just the bare necessities, to avoid coupling, dependencies, and ambiguities (e.g., what happens if a new class is added to the package with a name that conflicts with a name in another package?). That's why if you use Eclipse to organize your imports, it will actually add specific import statements inside of the asterisk version, even though that means extra lines. Importing everything in subpackages would be even worse, you'll really get everything.

    In addition, a common practice is to put special purpose classes and implementation-specific classes,in their own subpackages. Often, you specifically want to avoid importing them unless crucial. Again, importing the entire subtree would conflict with that.

提交回复
热议问题