|
|
Language Fundamentals - Import Declarations
Syntax
import packageName.*; // type-import-on-demand
import packageName.ClassName; // single-type-import
import packageName.InterfaceName; // single-type-import
- the import statement is used to reference classes and interfaces declared in other packages
- the type-import-on-demand import statement will cause the package to be searched when a type is declared for a class which has not been declared within the source file
- duplicate type-import-on-demand statements are ignored (JLS §7.5.2)
- the java.lang package is automatically imported in every compilation unit, it does not have to be specifically imported
- you can access classes and interfaces from other packages without first importing them but you must use their fully qualified names For example:
If you import the java.awt.Button class by using:
import java.awt.*; ,or,
import java.awt.Button;
You can create a Button by coding:
Button myButton = new Button();
Without the package import you'd need to code:
java.awt.Button myButton = new java.awt.Button();
Also see
Tips
- a single-type import will take precedence over an import-on-demand
- import-on-demand types do not increase the size of the compiled code ie only the types actually used are added to the code
- I've read that while import-on-demand adds no overhead to the compiled code, they can slow down the speed of the compile; however, Peter van der Linden, in Just Java 2, 4th Edition says it ain't so and my guess is he knows ... he's a kernel programmer for Sun
Traps
- single-type imports for two classes in different packages but with the same simple name
- single-type import with the same simple name as a class defined in the source file
- attempting to import a package vs a type ie import java.util vs import java.util.*
|