Java Reference
In-Depth Information
The one import-on-demand declaration in the above code has the same effect as the following two single-
type-import declarations:
import com.jdojo.cls.Human; // Import Human class
import com.jdojo.cls.Table; // Import Table class
Which type of import declaration is better to use in your Java program: single-type import or import-on-demand?
It is simple to use the import-on-demand declaration. However, it is not readable. Let's look at the following code,
which compiles fine. Assume that class A and B are not in the com.jdojo.cls package.
// ImportOnDemandTest.java
package com.jdojo.cls;
import p1.*;
import p2.*;
public class ImportOnDemandTest {
public static void main(String[] args) {
A a; // Declare a variable of class A type
B b; // Declare a variable of class B type
}
}
Can you tell, by looking at the above code, the fully qualified names of the classes A and B ? Is class A in the
package p1 or p2 ? It is impossible to tell just by looking at the code the package to which classes A and B belong
because you have used import-on-demand declarations. Let's rewrite the above code using two single-type-import
declarations.
// ImportOnDemandTest.java
package com.jdojo.cls;
import p1.A;
import p2.B;
public class ImportOnDemandTest {
public static void main(String[] args) {
A a; // Declare a variable of class A type
B b; // Declare a variable of class B type
}
}
By looking at the import declarations, you can now tell that class A is in the package p1 and class B is in the
package p2 . A single-type import declaration makes it easy for readers to know which class is being imported from
which package. It also makes it easy to know the number and name of the classes used from other packages in your
program. This topic uses single-type import declaration in all examples, except in examples where I discuss import-
on-demand declarations.
Even though you are advised to use single-type-import declaration in your programs, you need to know some
tricky uses and implications of using both single-type import and import-on-demand declarations in the same
program. Subsequent sections will discuss them in detail.
Search WWH ::




Custom Search