Java Reference
In-Depth Information
import p1.*;
imports all types only from
p1
package. It will not import the
p1.p2.C2
class because the
C2
class is not in the
p1
package; rather it is in the
p2
package, which is a sub-package of
p1
. The asterisk at the end of an import-on-demand
declaration means all types only from the specified package. The asterisk does not mean sub-packages and types
inside those sub-packages. Sometimes programmers attempt to use multiple asterisks in an import-on-demand
declaration thinking that it will import types from all sub-packages too.
import p1.*.*; // A compile-time error
The above import-on-demand declaration results in a compiler error because it uses multiple asterisks. It does
not follow the syntax for an import-on-demand declaration. In an import-on-demand declaration, the declaration
must end with a dot followed by one and only one asterisk.
If you want to import both classes
C1
and
C2
, you need to use two import-on-demand declarations.
import p1.*;
import p1.p2.*;
You can rewrite the code for the
ClassAccessTest
class using an import-on-demand declaration.
// ClassAccessTest.java - Modified version uses import-on-demand
package com.jdojo.common;
// Import all types from the com.jdojo.cls package incuding the Human class
import com.jdojo.cls.*;
public class ClassAccessTest {
public static void main(String[] args) {
Human jack; // Use simple name of the Human class
}
}
When the compiler tries to resolve the simple name
Human
in the above code, it will use an import-on-demand
declaration to see if a
Human
class exists in
com.jdojo.cls
package. In fact, the asterisk in the
import
declaration will
be replaced by
Human
and then the compiler checks if the
com.jdojo.cls.Human
class exists. Suppose you have two
classes in the
com.jdojo.cls
package named
Human
and
Table
. The following code will compile with one import-on-
demand declaration:
// ClassAccessTest.java - Modified version uses import-on-demand
package com.jdojo.common;
// Import all types from com.jdojo.cls package including Human and Table classes
import com.jdojo.cls.*;
public class ClassAccessTest {
public static void main(String[] args) {
Human jack; // Use simple name of the Human class
Table t1; // Use simple name of the Table class
}
}