Java Reference
In-Depth Information
Import Declarations and Type Search Order
Import declarations are used to resolve simple names of types to their fully qualified names during compilation.
The compiler uses predefined rules to resolve the simple names. Suppose the following statement appears in a Java
program that uses a simple name A :
A var;
The Java compiler must resolve the simple name A to its fully qualified name during the compilation process.
It searches for a type referenced in a program in the following order:
The current compilation unit
Single-type import declarations
Types declared in the same package
Import-on-demand declarations
The above list of type search is not complete. If a type has nested types, the nested type is searched before looking
in the current compilation unit. I will defer the discussion of nested types until inner classes are discussed in Chapter 2
of the topic Beginning Java Language Features (ISBN: 978-1-4302-6658-7).
Let's discuss the rules for a type search using some examples. Suppose you have a Java source file (a compilation
unit) B.java whose content is as follows. Note that the file B.java contains declarations for two classes A and B .
// B.java
package p1;
class B {
A var;
}
class A {
// Code goes here
}
Class B refers to class A with its simple name when it declares an instance variable var of type A . When the B.java
file is compiled, the compiler will look for a type with the simple name A in the current compilation unit ( B.java file).
It will find a class declaration whose simple name is A in the current compilation unit. The simple name A will be
replaced with its fully qualified name p1.A . Note that both classes A and B are declared in the same compilation unit,
and therefore they are in the same package, p1 . The class B definition will be changed as follows by the compiler:
package p1;
class B {
p1.A var; // A has been replaced by p1.A by the compiler
}
 
Search WWH ::




Custom Search