Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 checkBox 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?

like image 507
dave Avatar asked Dec 22 '22 13:12

dave


1 Answers

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.

like image 129
Andreas Dolk Avatar answered Dec 26 '22 08:12

Andreas Dolk