How to understand and use Java package

Source: Internet
Author: User

How to understand and use Java package

From


A package in Java is a Class Library Unit. The package contains a group of classes which are organized together under a single namespace. The namespace is the package name. You can use the import keyword to import a package. For example, you can use import java. util. * to import all classes in the namespace java. util package. To import all the classes in this package, you can directly use the classes in this package in the following program after the package name is declared by import. For example:

import java.util.*public class SingleImport{public static void main(Strin[] args){ArrayList list=nwe ArrayList();}}

Here, ArrayList is java. A class in the util package, but the java is loaded because the import keyword is used for the program. util package, so here we have not seen the definition and declaration of the ArrayList class, nor have we seen any qualified names before this class, we can directly use this class.

The reason why we want to import the package name is to provide a mechanism for managing the namespace. We know that if both Class A and Class B contain A method f () with the same feature tag (parameter list (), even if the two methods f () are used in the same Code, there is no conflict because two different class names are prefixed as the qualified names, therefore, two methods do not conflict with each other even if they have the same name. But what if the class names conflict with each other? Suppose you have compiled an Apple class and installed it on a machine, and there is already an Apple class written by someone else on this machine. What should we do? It is not easy to find out which classes have been installed on a machine. Therefore, there is always a potential conflict between names. It is very important to fully control the namespace in Java and create a unique identifier combination for each class. If you want to write a class library or program that is friendly to other Java programs that coexist on the same machine, you need to consider how to prevent conflicts between class names.

When writing a Java source code file, this file is usually called a compilation unit. Each compilation unit must have a suffix. java, and there is only one public class in the compilation unit; otherwise, the compiler will not accept it. The public class name must be the same as the file name (including case, but not suffix. java ). If there are additional classes in the compilation unit, these classes cannot be seen outside the package because they are not public classes, they are mainly used to provide support for the primary public class.

When you compile. java files (that is, a compilation unit. each class in the java file has an output file, and the name of the output file and. each class name in the java file is the same, but an extension is added. class. Therefore, a large number of. class files are obtained after a small number of. java files are compiled. After each. java file is compiled, there will be a public class and any number of non-public classes. Therefore, each. java file is a component. If you want many such components to belong to the same group, you can use the keyword package in each. java file. This group is a class library.

If the package statement is used, it must be the first program code except comments in the. java file. If you write at the beginning of the file:

Package fruit;

It indicates that you are declaring the compilation unit as part of the class library named fruit, or in other words, you are declaring that the public class name in the compilation unit is under the umbrella of the fruit name, it is covered by the fruit name. Anyone who wants to use the public class name must specify the full name or use the keyword import with fruit.

For example, if the file name is Apple. java, this means that there is only one public class in the file, and the name of this class must be Apple (case sensitive ):

package fruit;public class Apple{//...}

The above code has included the Apple class in the fruit package. If you want to use any other public class in Apple or fruit, you must use the keyword import to make the name in fruit available.

import fruit.*;public class ImportApple{public static void main(String[] args){Apple a=new Apple();}}

Or use the full qualified name:

public class QualifiedApple{public static void main(String[] args){fruit.Apple a=new fruit.Apple();}}

Obviously, the keyword import is used to make the code more concise.

As a programmer, we should remember that the package and import keywords allow us to split a single global namespace into separate and closed namespaces, so that no matter how many people use the Internet or Java to write classes, there will be no conflict with our class names, because our classes are enclosed in our own defined independent namespaces, rather than in public global namespaces.

Here, you may find that the so-called keyword package never packs packaged items into a single file, and a package can be composed of many. class file structure, which may include two classes with the same name into a package. To avoid this, a logical approach is to put all the specified. class files in one directory. That is to say, the hierarchical file structure of the operating system is used to solve this problem. This is a way for Java to solve the confusion problem (the JAR package tool is not discussed here ).

Revenue from all files into one sub-directory can solve two other problems: 1. How to create a unique name; 2. How to find classes that may be hidden in a directory structure.

These tasks are implemented by coding the path and location of the. class file to name the package name.

By convention, the first part of the package name is the reverse-order Internet Domain Name of the class creator. Why use an Internet domain name? If you follow the conventions, the Internet domain name should be unique, so your package name will also be unique, that is, the custom independently closed namespace mentioned above will be unique, so that there will be no name conflict issues. Of course, if you do not have your own domain name, you have to create a unique package name by creating a group of combinations that are unlikely to be repeated with others (such as your name. If you plan to release your Java program code, it is necessary to get a domain name at a slight cost.

In addition, if your Java program code is only run on a local computer, you can also break down the package name into a directory on your machine. Therefore, when the Java program runs and the. class file needs to be loaded, it can determine the location of the. class file in the directory based on the package name.

How to determine the position of the. class file when the program is running?

Let's take a look at the running process of the Java interpreter: First, find the environment variable CLASSPATH (which can be set through the operating system ). CLASSPATH contains one or more directories and is used to find the root directory of the. class file. Starting from the root directory, the interpreter obtains the package name and replaces each period with a backslash to generate a path (for example, package fruit. apple becomes fruit/Apple or others, depending on the operating system ). The obtained path is connected to different root directory paths in CLASSPATH to obtain a complete directory path, in these directories, the interpreter finds the class names that are the same as those you need. class file. (In addition, the interpreter searches for Standard Directories that involve the location of the Java interpreter .)

To understand this, take the domain name Food.net as an example. Convert the order of the class to lowercase. net. food is a unique namespace for creating classes. If we decide to create another class library named fruit, we can further segment the name, so we get a package name as follows:

Package net. food. fruit;

Now, the package name can be used as the namespace umbrella for the following Apple file:

package net.food.fruit;        public class Apple    {    public Apple(){System.out.println("net.food.fruit.Apple");}    }

This file may be placed in the following directory in the computer system:

C:/DOC/JavaT/net/food/fruit

The reason for storing the file in this directory is that, as mentioned above, the CLASSPATH environment variable is used to locate the file. Looking back at this path, we can see the package name net. food. fruit. But what about the First Half of the path? To the environment variable CLASSPATH, we can set the environment variable CLASSPATH in the computer as follows:

CHASSPATH =.; D:/JAVA/LIB; C:/DOC/JavaT

CLASSPATH can contain multiple available query paths. Each path is separated by semicolons. The third path of the CLASSPATH environment value above is the root directory of the preceding file. As mentioned above, the Java interpreter first finds the root directory C:/DOC/JavaT, and then maps it with the package name net. food. fruit is connected, and the period in the package name is converted into a slash during the connection, the complete class file path C:/DOC/JavaT/net/food/fruit is obtained.

Note that the CLASSPATH environment variables take care of the class files in the package. If you take care of the class files in the JAR package, there will be a slight change, that is, the actual name of the JAR file must be clearly written in the CLASSPATH environment variable path, instead of specifying the directory where the JAR package is located. As you can imagine, there may be many other JAR packages in the directory where the JAR package is located, and the class file we need to use will only exist in one of the JAR packages, so we can understand it as follows, here, the JAR package actually acts as the first-level file directory, so you need to clearly write the JAR package file name in the CLASSPATH environment variable. For example, if the Apple file exists in a jar file named fruit. JAR, CLASSPATH should write:

CLASSPATH =.; D:/JAVA/LIB; C:/DOC/JavaT/net/food/fruit. jar

Once the path is correctly created, the following files can be stored under any directory:

import net.food.fruit.*;public class LibTest{public static void main(String[] args){Apple a=new Apple();}}
When the compiler encounters the import Statement of the fruit database, it starts to search in the directory specified by CLASSPATH, during the search process, the root directories set in CLASSPATH are connected with the sub-directories net/food/fruit converted by the package name, find the compiled file (that is, the class file) in the complete directory after the connection to find the name that matches (for Apple, It is Apple. class ). The file matches the Apple class.

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.