Java package (translated from Java tutorials)

Source: Internet
Author: User

From http://www.cnblogs.com/ggjucheng/archive/2012/12/17/2821935.html

English from http://docs.oracle.com/javase/tutorial/java/package/summary-package.html

Package

This section describes how to bind classes and interfaces to a package, how to use classes in the package, how to classify classes in the file system, and how to let the compiler find yourSource code.

 

Create and use packages

In order to make it easier to search and use types, avoid name conflicts and access control,ProgramStaff should bundle related types into packages.

Statement: Packages are related groups that provide access control and namespace management. Note that the types are class, interface, enumeration, and annotation. Enumeration and annotation types are special classes and interfaces. Therefore, the types in this section are generally called classes and interfaces. Some types of the Java platform are members of various software packages of function bundle classes: basic classes in Java. Lang, read and write classes (input and output) in Java. Io. You can also put your type in the bag.

Suppose you want to write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. You can also write an interface, draggable, which is implemented when you need to be dragged by the mouse.

// In the draggable. java filepublic interface draggable {...} // In the graphic. java filepublic abstract class graphic {...} // In the circle. java filepublic class circle extends graphic implements draggable {...} // In the rectangle. java filepublic class rectangle extends graphic implements draggable {...} // In the point. java filepublic Class Point extends graphic implements draggable {...} // In the line. java filepublic class line extends graphic implements draggable {...}

 

Bind classes and interfaces to a package force for the following reasons:

You and other programmers can easily see that these classes are related.

You and other programmers know where to find the type that provides graphic-related methods.

Because the Package creates a new namespace, the name of your type does not conflict with the name of another package type.

The type of the same package is allowed. Access between classes is not strictly controlled, but access to classes outside the package is strictly controlled.

 

Create package

To create a package, you can select the package name (the naming convention will be discussed in the next section). This name is at the top of each of the above source files, including the types (classes, interfaces, enumeration and annotation, and the package statement type) must be in the package.

The package statement (for example, package graphics;) must be the first line of the source code file. Each source code file can have only one package statement, which applies to all types of source code files.

Note: A single source code file creates multiple types. Only one class can be declared as public, and its name must be the same as that of the source code file. For example, in the circle. Java file, you can declare public class circle in the draggable. Java file. Public interface draggable, declared in the day. Java FilePublic Enum DYA, and so on. You can include a non-pubilc type in the same file (this is strongly not recommended unless the Non-Public type is closely related to the corresponding public type and the access scope is smaller ), however, only the public type can be accessed outside the package. All top-level non-public types are private packages. If you want to put the image interfaces and classes in the package named graphics in the previous chapter, you need six source code files, as shown below:
// In the draggable. java filepackage graphics; public interface draggable {...} // In the graphic. java filepackage graphics; public abstract class graphic {...} // In the circle. java filepackage graphics; public class circle extends graphic implements draggable {...} // In the rectangle. java filepackage graphics; public class rectangle extends graphic implements draggable {...} // In the point. java filepackage graphics; public class point extends graphic implements draggable {...} // In the line. java filepackage graphics; public class line extends graphic implements draggable {...}

If the package statement is not used, the type is in an anonymous package. Generally, an anonymous package is only a small scope or temporary program used for deployment. Otherwise, the class and interface must belong to the named package.

 

Name package

When programmers around the world use JavaProgramming Language, Write class and interface, it is very likely that many programmers name the same name for different types. In fact, the previous example is to do this: it declaresRectangle class, and Java. AWT package also hasRectangle class. However, if they are in different packages, the compiler allows two classes to have the same name. The fully qualified name of each rectangle class contains the package name. This indicates that the fully qualified name of the rectangle class of the graphics package is graphics. rectangle. The fully qualified name of the rectangle class of the Java. AWT package is Java. AWT. rectangle.

This works well unless two independent programmers use their own packages with the same name. How can this problem be prevented? Convention.

 

Naming Convention

The package name must be in lower case to avoid name conflicts between classes and interfaces.

The company uses reverse Internet domain names as the beginning of their package names-for example, Com. example. mypackage is a programmer at example.com who creates a package named mypackage.

Naming conflicts within the company are solved by the company's convention, which may include the region or project name (for example, Com. example. region. mypackage) after the company name)

The Java language package starts with Java. Or javax.

In some cases, the Internet domain name is not a valid package name. If the domain name contains one or other special characters, if the name starts with a number or other characters, it is invalid to use the Java name, or the package name contains a Java reserved keyword, such as Int. In this case, we recommend that you add an underline, for example:

Legal package name
Domain Name Package name prefix
Hyphenated-name.example.org Org. example. hyphenated_name
Example.int Int _. Example
123name.example.com Com. example. _ 123 name

 

 

Use package members

The type of the component package. It is well known that it is a member of the package.

To use public package members outside the package, you must do one of the following:

Reference a member by fully qualified name

Import package members

Import the complete package of the member

Each type applies to different situations, as described in the following chapter.

Reference a member by fully qualified name

So far, the most common examples in the tutorial are to reference classes by their concise names, suchRectangle and stackofints. Reference a package member by simple name, which can beCodeIt is written in the same package of the package member, or the member has been imported.

However, if you try to use different package members, and this package is not imported, you must use the fully qualified member name, which includes the package name. Here is the fully qualified name of the rectangle class declaration in the graphics package:

 
Graphics. rectangle

Use a fully qualified name to create a graphics. Rectangle instance:

 
Graphics. Rectangle myrect = new graphics. rectangle ();

The number of fully qualified names is relatively small. However, repeated use of a name makes it tedious to enter a name repeatedly and makes the code hard to read. (Optional) You can import a member or its package and use its simple name.

 

Import package members

To import a specific member to the current file, the import statement should be placed at the beginning of the file, before any type declaration, but behind the package statement, if there is a package statement. Here is an example of importing the rectangle class of the graphics package in the previous example:

 
Import graphics. rectangle;

You can reference the rectangle class by its concise name.

Rectangle myrectangle = new rectangle ();

This is close to working well if you are only using a few members of the graphics package. However, if you use many types of packages, you should import the complete package.

 

Import Full package

To import all types of a specific package, use the import statement with the wildcard asterisk.

 
Import graphics .*;

Now you can use a simple name to reference any class and interface of graphics.

 
Circle mycircle = new circle (); rectangle myrectangle = new rectangle ();

The import statement with a star number can only be used to specify all classes of the package, as shown in. It cannot be used for the classification of matching packages. For example, the following method does not match the class starting with a in the graphics package.

 
//Does not workImport graphics. *;

On the contrary, it produces a compiler error. The Import Statement can only be used to import one package member or one full package.

Note: Non-commonly used import statements allow the import of Public Nested classes of encapsulation classes. For example, if the graphics. Rectangle class contains useful Nested classes, such as rectangle. doublewide and rectangle. Square, you can use the following two statements to import rectangle and Its Nested classes.
 
Import graphics. rectangle; import graphics. Rectangle .*;
Note that the second statement does not import rectangle. Another non-commonly used import and static import statement will be discussed later. By convention, the Java compiler automatically imports two full packages for each source code file: (1) Java. lang Package and (2) current package (package of the current source code file) Apparently hierarchical package

First, packages are layered, but they are not. For example, Java APIs include Java. AWT packages, java. AWT. Color packages, java. AWT. Font packages, and many other packages starting with Java. AWT. However, the Java. AWT. Color package, java. AWT. font package, and other Java. AWT. xxxx packages are not included in the Java. AWT package. The prefix java. AWT (Java Abstract Window tool) is used to make some related packages more explicit, but not display the inclusion.

Import Java. AWT. * import Java. all types of the AWT package, but it does not import Java. AWT. color, Java. AWT. font, or other Java. AWT. any class of the XXX package. If you want to import all types of Java. AWT. color to Java. AWT, you must import two packages in the source code file:

 
Import java. AWT. *; import java. AWT. color .*;

Name Ambiguity

If the name of a package member is the same as that of another package member, and both packages are imported, each member must be referenced by their fully qualified name. For example, graphics declares a class rectangle, and the java. AWT package also contains the rectangle. If graphics and Java. AWT are both imported, the following statements are ambiguous.

 
Rectangle rect;

In this case, the fully qualified name of the member must be used to indicate exactly which rectangle class you want to import. For example:

 
Graphics. Rectangle rect;

Static Import Statement

Here is a method, when you need to frequently access the static fields (constants) and static methods of one or two classes. The names of these classes are often used as prefixes, leading to code confusion. The static import statement provides a static constant and static method required for the import so that you do not need to use their class names as prefixes.

The Java. Lang. Math class declares the constant PI and many static methods, including sine, cosine, tangent, square root, maximum, minimum, exponent, and many other methods. For example:

 
Public static final double Pi = 3.141592653589793; public static double cos (double ){...}

Generally, to use these objects from a class, you must use the class name as the prefix, as shown below:

 
Double R = math. Cos (math. Pi * theta );

You can use a static Import Statement to import the static members of Java. Lang. Math without using the class name prefix math. The static members of math can be imported independently:

 
ImportStaticJava. Lang. Math. Pi;

Or import a group:

 
ImportStaticJava. Lang. Math .*;

Once they are imported, the use of static members does not require a qualifier. For example, the previous code snippet will become:

 
Double R = cos (pI * theta );

Obviously, when writing your own class, you can include frequently used variables and static members, and then use static import statements. For example,

ImportStaticMypackage. myconstants .*;
Note: Exercise caution when using static import. Excessive use of static import may make the code difficult to read and maintain, because the code reader does not know which class defines a specific static object. Properly used, static import, and deletion of duplicate class names make the code more readable. Manage source code and class files

The implementation of many Java platforms relies on hierarchical file systems to manage source code and class files, even though Java language specifications are not required. The policy is as follows.

Class, interface, enumeration, or annotation type source code will be in a text file, its name is a simple type name, its extension is. java. For example:

 
// In the rectangle. Java file package graphics; public class rectangle {...}

Then, put the source code in a directory, and the directory name corresponds to the name of the package of the type:

 
... \ Graphics \ rectangle. Java

The qualified name of the package member is parallel to the file path. Assume that the delimiter backslash is used for Microsoft Windows File Names (a forward slash is used for UNIX ).

    • Class Name-Graphics. rectangle
    • File Path-Graphics \ rectangle. Java

As you will review, the company uses the reversal of its Internet domain name as the package name. For example, its Internet domain name is example.com. All its package names start with COM. example. Each element of the package name corresponds to a sub-directory. Therefore, if example has a com. example. graphics package containing a rectangle. Java source file, it will contain a series of subdirectories similar to the following:

 
... \ Com \ example \ graphics \ rectangle. Java

When a source file is compiled, the compiler creates different output files for each type of the source file. The basic name of the output file is the type name, and its extension is. Class. For example, if a source code file is similar to the following:

 
// In the rectangle. Java filepackage com. example. graphics; public class rectangle {...} class helper {...}

Then the compiled file will be located:

 
<Path to the parent directory of the output files> \ com \ example \ graphics \ rectangle. class <path to the parent directory of the output files> \ com \ example \ graphics \ helper. class

For example, for the. Java source file, the compiled. Class file should be located in a series of directories corresponding to the package name. However, the path of the. Class file does not have to be the same as that of the. Java source file. You can configure the source code and the directory of the class file independently, for example:

 
<Path_one> \ sources \ com \ example \ graphics \ rectangle. Java <path_two> \ Classes \ com \ example \ graphics \ rectangle. Class

In this way, you can give the class directory to other programmers without the source code. You also need to manage source code and class files in this way so that the compiler and Java Virtual Machine (JVM) can find all types used by your program.

The full path of the classes directory, <path_two> \ Classes, is called the class path, which is set by the classpath system variable. Both the compiler and JVM Add the package name to the class path to construct the path to the. Class file. For example, if

 
<Path_two> \ Classes

Is your class path and the package name is

 
Com. example. Graphics,

Then the compiler and JVM find the. Class file in

 
<Path_two> \ Classes \ com \ example \ graphics.

A class path can contain multiple paths separated by semicolons (Windows) or colons (UNIX. By default, the compiler and JVM will find the current directory and jar files containing the Java platform class, so these directories will be automatically added to the class path.

Set the class path system variable

To display the current classpath variable, run the following command in windows and Unix (Bourne shell:

 
In Windows: C :\> set classpathin Unix: % echo $ classpath

 

To delete the current content of the classpath variable, run the following command:

 
In Windows: C :\> set classpath = in UNIX: % unset classpath; export classpath

 

Set the classpath variable and use the following variable (example ):

 
In Windows: C :\> set classpath = c: \ Users \ George \ Java \ classesin Unix: % classpath =/home/George/Java/classes; export classpath
 
 
Summary of creating and using packages

Create a package for the type. The package statement should be placed in the first line of the source file where the type (class, interface, enumeration, annotation) is located.

Use the public type in different packages. There are three options: (1) use the full qualifier of the type (2) Import Type (3) complete package of the Import Type

The path name of the source file and class file of a package is the image of the package name.

You need to set your own classpath, and then the compiler and JVM can find the. Class file based on your type.

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.