Java import confusion

2020-02-12 01:29发布

问题:

What is the difference between:

java.awt.*;

and:

java.awt.event.*;

I find both in many programs.

回答1:

Packages in Java are not nested.

When you import java.awt.*, you are only importing all the classes and interfaces that are in the package java.awt - you are not importing all the packages that are under java.awt, such as java.awt.event.

Even though it looks like packages are nested (i.e., it looks like as if java.awt.event is a "subpackage" of java.awt), this is not really the case. You should regard java.awt and java.awt.event as two different, unrelated packages that happen to have a common part in their names.



回答2:

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.



回答3:

Like many have said before.

import java.awt.* won't import any classes in java.awt.event...

And the difference between those two package is that java.awt.* include classes like a Frame, Button, etc and the java.awt.event.* package include all event / listener that can happen.

Example, to create a Button you need the class java.awt.Button but if you want that any action happen when you click the Button, you need a java.awt.event.ActionListener that will "wait" for the click, then produce a java.awt.event.ActionEvent.



回答4:

java.awt.* is not a regular expression, which is what I think you are expecting/thinking.

java.awt.* will give you only the classes in that exact package, and not the nested packages. Imagine the name space collisions involved with below!

import com.*

It should be noted that it is considered bad practice to use *. Explicate class name imports are preferred.

For further reading: Wikipedia: Namespace (Computer Science)



标签: java import