What does the package do

The Chinese meaning of package is "package", which is a relatively abstract logical concept. Its purpose is to convert .java files (Java source files), .class files (compiled files) and other resource files (for example, .xml files) . , .avi files, .mp3 files, .txt files, etc.) are organized in an organized manner for use.

It is similar to a Linux file system, there is a root, from the root there are directories and files, and then directories are nested within directories.

Specifically, the package package mainly has the following two functions:

First, it provides a multi-layered namespace to resolve naming conflicts. By using packages, classes in different packages can have the same name.

Second, categorize classes by function to make the organization of the project clearer. When developing a project with a large number of classes, if you do not use packages to classify classes, but put all classes under one package, the readability of the code is poor, and the maintainability is also poor, which will seriously affect the development efficiency.

The usage of package is generally as follows (the directory where the source file is located is the current directory):

1) Add "package packagename;" at the beginning of each source file, and then create a new directory named packagename under the directory where the source file is located.

2) Compile each sourcename.java source file with the javac command, and copy the generated sourcename.classname file to the packagename directory.

3) Run the program with the java command: java.packagename.sourcename.

The following is a simple program example:

package com.pkg;

public class TestPackage{undefined

public static void main(String[] args)

System.out.println("Hello world");


        Compile the code by running the command java-d.TestPackage.java, the directory com/pkg will be automatically generated in the current directory, and then execute the program by running the command java com.pkg.TestPackage, the result of the program is:

 Hello World

Common written test questions:

Which of the following statements is correct:

A. The main role of packages in Java is to implement cross-platform functions

B. The package statement can only be placed after the import statement

C. A package consists of a set of classes and interfaces

D. You can use the #include keyword to indicate that it comes from other package types

Answer: C

Tags: What does the package do

java elementary p2p android Network protocol

Related: What does the package do