开发者

what is the need for importing libraries multiple times

in most code examples I see people doing this.

import javax.swing.*; // for the frame
import java.awt.*; // for the checkBox and the label
import java.awt.event.*; // for the checkBo开发者_C百科x listener

If I am correct when we say import java.awt.* it imports everything inside it, so there wont be a need to say import java.awt.event.*; or is there a speed improvement? can anyone also explain what importing a library does, is it importing a simple text class to be included in the source or telling jvm to include the byte code of whatever is imported? so importing in java does nothing but switch the namespace, so I dont have to type long class names?


Forget the term subpackage. Do it quick. It does not exist in java world.

java.awt is a package (namespace), java.awt.event is another one and they have nothing in common. Their names share some characters, but the packages are totally unrelated. The import statements imports a class or some classes from exactly one package (namespace). If you need classes from a different package (namespace), then you have to add another import statement.


BTW, in response to a comment to another answer: You do not have to use import statements. If you don't use them, you simply have to use the fully qualified classnames in your java source file (except: classes from java.lang and the current package are imported automatically). So import could be considered as a convenient way to keep the code readable.

Importing is not required in order to use a class in your source file.


The line...

import java.awt.*;

...doesn't mean that all subpackages will also be imported. You have to explicitly import every package. As an example, importing java.* doesn't give you the entire java library.

For what it's worth, I recommend importing the specific classes only unless you have good reason to use *.


Importing a package doesn't import its subpackages.

Importing is about switching the namespace, too.

If you only had import java.awt.* and you were to use the class java.awt.Outer.Inner, everywhere in your code you have to refer to it as Outer.Inner.

By contrast, when you say import java.awt.Outer.*, you can refer to the inner class as just Inner.


Importing is just a compile time feature, in bytecode you will find only direct references to specific classes, everytime its instance is used. "import" constructs exist just to eliminate use of full class name everytime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜