A class may need an object declared by another class as its own member or local variable in a method. If the two classes are in the same package, there is no problem. However, if the two classes are not in the same package, this The import statement must be used.
Import classes from the class library
Use the import statement to introduce classes in the package. When writing source files, in addition to writing classes yourself, you often need to use many classes provided by Java, which may be in different packages.
In order to use the classes provided by Java, you can use the import statement to introduce classes in the package. There can be multiple import statements in a Java source program, and they must be written between the package statement (if there is a package statement) and the definition of the class in the source file. Java provides about 130 packages.
For example:
java.lang contains all basic language classes
java.io contains all input and output classes
java.util contains utility classes
java.sql contains classes for operating databases
java.net contains all classes that implement network functions
If you want to introduce all classes in a package, you can use the wildcard symbol asterisk (*) instead, for example:
importjava.util.*;//Indicates the introduction of all classes in the java.util package importjava.util.Date;//Indicates the introduction of the Date class in the java.util package
Import classes from custom packages
User programs can also use the import statement to introduce classes with package names in non-class libraries, for example:
importtom.jiafei.*;
In order to enable their own programs to use the classes in the tom.jiafei package, users can specify the location of the tom.jiafei package in the classpath. Assume that the location of the package tom.jiafei is C:1000, that is, the class with the package name tom.jiafei The bytecode is stored in the C:1000tomjiafei directory. Users can update the value of classpath, for example:
setclasspath=C:jdk1.6jrelibrt.jar;.;C:1000/* means that the unnamed package class in the C:1000 directory can be loaded and the descendant directories in the C:1000 directory can be used as Package name to use */
If the user does not want to update the classpath value, the user can create a subdirectory structure corresponding to the package in the directory where the user program is located.
For example: the directory where a certain class in the user program is located is C:2000. If this class wants to use the import statement to introduce the class in the tom.jiafei package, then create a directory structure C:2000tomjiafei based on the package name. There is no need to go Modify the value of classpath, because the default classpath value is:
C:jdk1.6jrelibrt.jar;.;/* ".;" means that the unnamed package class in the current directory of the application can be loaded and the descendant directory under the current directory can be used as the name of the package* /