Java Reference
In-Depth Information
Single-Type Import Declaration
A single-type import declaration is used to import a single type (e.g. a class) from a package. It is of the form
import <<fully qualified name of a type>>;
The following import declaration imports the
Human
class from the
com.jdojo.cls
package:
import com.jdojo.cls.Human;
A single-type import declaration imports only one type from a package. If you want to import more than one type
(e.g. three classes) from a package (or from different packages), you need to use a separate import declaration for each
type. The following import declarations import
Class11
from
pkg1
package,
Class21
and
Class22
from
pkg2
package,
and
Class33
from
pkg3
package:
import pkg1.Class11;
import pkg2.Class21;
import pkg2.Class22;
import pkg3.Class33;
Let's revisit the
com.jdojo.common.ClassAccessTest
class, which had a compile-time error.
// ClassAccessTest.java
package com.jdojo.common;
public class ClassAccessTest {
public static void main(String[] args) {
Human jack;
}
}
You received a compiler error when you used the simple name of the
Human
class because the compiler could not
find a
Human
class in the
com.jdojo.common
package. You resolved this error by using the fully qualified name of the
Human
class, like so:
// ClassAccessTest.java
package com.jdojo.common;
public class ClassAccessTest {
public static void main(String[] args) {
com.jdojo.cls.Human jack; // Uses full qualified name for the Human class
}
}
You have another way to resolve this error, which is by using a single-type-import declaration. You can import the
com.jdojo.cls.Human
class to its simple name. The modified
ClassAccessTest
class declaration is as follows:
// ClassAccessTest.java - Modified version
package com.jdojo.common;
import com.jdojo.cls.Human; // Import the Human class