Learning: examples of using & quot; package & quot; and & quot; import & quot; in java, packageimport

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.