Java Reference
In-Depth Information
public class ClassAccessTest {
public static void main(String[] args) {
Human jack; // Use simple name of the Human class
}
}
The modified version of the ClassAccessTest class compiles fine. When the compiler comes across the simple
name of the Human class in the statement, like
Human jack;
it goes through all import declarations to resolve the simple name to a fully qualified name. When it tries to resolve the
simple name Human , it finds the import declaration, import com.jdojo.cls.Human , which imports the Human class. It
assumes that you intended to use the com.jdojo.cls.Human class when you used the simple name Human in the above
statement. The compiler replaces the above statement with the following statement:
com.jdojo.cls.Human jack;
Import declarations let you use the simple name of a type in your code, thus making your code more readable.
When you compile your code, the compiler replaces the simple name of a type with its fully qualified name. It uses import
declarations for converting simple names of the types to their fully qualified names. It is to be emphasized that using
import declarations in your java program does not affect the size of your compiled code or runtime performance. Using
import declarations is just a way to use the simple names of classes in your source code.
Tip
There are many subtle points to remember while using import declarations. I will discuss them shortly.
Import-on-Demand Declaration
Sometimes you may need to import multiple types from the same package. You need to use as many single-type-
import declarations as the number of types you need to import from the package. An import-on-demand declaration
is used to import multiple types from a package using one import declaration. The syntax for an import-on-demand
declaration is
import <<package name>>.*;
Here, the package name is followed by a dot and an asterisk ( * ). For example, the following import-on-demand
declaration imports all types (that includes all classes) from com.jdojo.cls package:
import com.jdojo.cls.*;
Sometimes the use of an asterisk in an import-on-demand declaration leads to wrong assumption about the
types that are imported. Suppose there are two classes, C1 and C2 . They are in packages p1 and p1.p2 , respectively.
That is, their fully qualified names are p1.C1 and p1.p2.C2 . You may write an import-on-demand declaration as
import p1.*;
thinking that it will import both classes, p1.C1 and p1.p2.C2 . This assumption is wrong. The declaration
 
 
Search WWH ::




Custom Search