Learning: Examples of "package" and "import" in java: packageimport
1. What problems does package solve?
Provides a namespace for classes to solve class naming conflicts and class file management problems.
2. Example
2.1 self-test code
(1) The package must be the first non-Comment statement in the source file.
(2) One source file can only have one package
(3) If no display is specified, it is in the default package.
(4) Free access under the same package
1 package testPkg; 2 3 public class testPackage{ 4 public static void fun1(){ 5 System.out.println("Msg: testPackage print"); 6 } 7 8 public static void main(String[] args){ 9 fun1();10 }11 }
View Code
1 import testPkg.testPackage;2 3 public class testCallPackage{4 public static void main(String[] args){5 testPackage.fun1();//testPkg.testPackage.fun1();6 }7 }
View Code
2.2 execution
(1) Use-d whenever possible during compilation. the compiler will generate the corresponding directory structure for the java source file.
(2) Compile 1 to generate the "testPkg" Directory
(3) Compile 2 to generate "testCallPackage. class"
3. Use of import
(1) You do not need to add the package name during the call.
(2) If the two packages contain the same class name, only the package. XXX. function format can be used. import causes compilation fuzzy errors.
(3) import static: You can import static variables.
4. General Structure of java source files