How to understand and use Java package packages

Source: Internet
Author: User

A package in Java is a class library unit that contains a set of classes that are organized together under a single namespace. This namespace is the package name. You can import a package by using the Import keyword. For example, using Import java.util.*, you can import all the classes in the namespace Java.util package. The so-called import of all the classes in this package, that is, after the import declaration of the package name, in the next program can directly use the class in the package. For example:

[Java]View Plain Copy
    1. Import java.util.*
    2. public class Singleimport
    3. {
    4. public static void Main (strin[] args)
    5. {
    6. ArrayList list=nwe ArrayList ();
    7. }
    8. }

Here ArrayList is a class in the Java.util package, but because the program uses the Import keyword to load the java.util package, so there is no definition and declaration of the ArrayList class, and do not see the class in front of what the qualified name, you can directly use this class.

The reason we want to import the package name is to provide a mechanism for managing the namespace. We know that if there are two classes of Class A and Class B that have a method F () with the same signature (parameter list), there will be no conflict even if both methods F () are used in the same piece of code, because there are two different class names in front as qualified names. So two methods, even if they have the same name, do not return a conflict. But what if the class names collide with each other? Suppose you wrote an Apple class and installed it on a machine that already had an Apple class written by someone else, how do we fix it? Because if you want to figure out which classes are installed on a machine, it's not an easy thing to do, so there's always the possibility of a potential conflict between names. Having full control over namespaces in Java and creating unique combinations of identifiers for each class is a very important thing. If you are writing other Java program-friendly class libraries or 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 often referred to as a compilation unit. Each compilation unit must have a suffix name. java, and there is only one public class within the compilation unit, otherwise the compiler will not accept it. The public class must have the same name as the file (including case, but not suffix. java). If there are additional classes in the compilation unit, these classes cannot be seen in the world outside the package because they are not public and are primarily used to provide support for the primary public class.

When compiling a. java file (that is, a compilation unit), each class in the. java file will have an output file with the same name as each class in the. java file, with just one more suffix. class. Therefore, after compiling a small number of. java files, you will get a large number of. class files. Every. java file is compiled with a public class and any number of non-public classes. So every. java file is a component, and if you want many of these artifacts to belong to the same group, you can use the keyword package in each. java file. And this group is a class library.

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

Package fruit;

It means that you are declaring that the compilation unit is part of a 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 and is shaded 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, suppose the name of a file is Apple.java, which means that there is only one public class in the file, and the name of the class must be Apple (note case):

[Java]View Plain Copy
    1. Package fruit;
    2. public class Apple
    3. {
    4. //...
    5. }

The code above already contains the Apple class in the fruit package, and now if someone wants to use Apple or any other public class in fruit, they must use the keyword import to make the name available in fruit.

[Java]View Plain Copy
    1. Import fruit.*;
    2. public class Importapple
    3. {
    4. public static void Main (string[] args)
    5. {
    6. Apple a=new Apple ();
    7. }
    8. }

Or use the fully qualified name:

[Java]View Plain Copy< param name= "flashvars" value= "id=4&width=18&height=18" >
    1. public class Qualifiedapple
    2. {
    3. public static void Main (string[] args)
    4. {
    5. Fruit. Apple a=new fruit. Apple ();
    6. }
    7. }

Obviously using the keyword import makes the code more concise.

As a programmer, we should keep in mind that the package and import keywords allow you to split a single global namespace into separate, closed namespaces, so that no matter how many people use the Internet and Java to start writing classes, there is no problem with our class names. Because our class is enclosed in a separate namespace of our own definition, not in the public global namespace.

Here you may find that the so-called keyword package packaging has never packaged things into a single file, and a package can be made up of many. class files, and there is the possibility of hitting two of the same classes into a package. To avoid this, it is a logical practice to place all of the. class files in a single directory. In other words, the hierarchical file structure of the operating system is used to solve this problem. This is a way for Java to solve the chaos problem (the JAR package tool is not discussed here for the moment).

Earning all of your files a subdirectory can also solve two other problems: how to create a unique name, and how to find a class that might be hidden somewhere in the directory structure.

These tasks are implemented by coding the path location where the. class file is located, called the package name.

By convention, the first part of the package name is the anti-order Internet domain name of the creator of the class. Why use an Internet domain name? Because if you follow the Convention, the Internet domain name should be unique, so your package name will be unique, and the previously mentioned custom, separate, closed namespace will be unique, so there will be no problem with name collisions. Of course, if you don't have your own domain name, you have to construct a set of unique package names that are unlikely to be duplicated by others (such as your name). If you are going to publish your Java program code, it is still necessary to take a bit of the cost to get a domain name.

Also, if your Java program code is only running on the local computer, you can break the package name into a directory on your machine. So when the Java program runs and needs to load the. class file, it can determine the location of the. class file on the directory based on the package name.

How does the program determine the location of the. class file when it is running?

Let's take a look at the Java interpreter's running process: First, find out the environment variable classpath (which can be set by the operating system). Classpath contains one or more directories that are used as the root directory for finding. class files. Starting at the root, the interpreter obtains the package name and replaces each period with a backslash to produce a path from the classpath root (for example, the packages fruit. Apple becomes fruit/apple or fruit/apple or other, which will depend on the operating system). The resulting path is connected to each of the different root paths in the classpath to get a complete directory path where the interpreter looks for the same. class file as the class name you need. (in addition, the interpreter will look for some standard directories involving the location of the Java interpreter.) )

To understand this, take the domain name Food.net as an example. Turning it upside down and converting it all to lowercase, Net.food is a unique namespace for creating classes. If we decide to create another class library named fruit, we can subdivide the name further, so we get a package with the following name:

Package net.food.fruit;

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

[Java]View Plain Copy< param name= "flashvars" value= "id=5&width=18&height=18" >
    1. Package net.food.fruit;
    2. public class Apple
    3. {
    4. Public Apple ()
    5. {
    6. System.out.println ("Net.food.fruit.Apple");
    7. }
    8. }

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

C:/doc/javat/net/food/fruit

The reason to put this in this directory is because of the above mentioned, so that the system through the CLASSPATH environment variable to find this file. Look back along this path to see the package name Net.food.fruit, but what about the first half of the path? Give 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 query paths to choose from. Each path is separated by a semicolon, and you can see that the third path to the CLASSPATH environment value above is the root of our previous file. As mentioned earlier, the Java interpreter will first find the root directory C:/doc/javat, and then connect it to the package name Net.food.fruit, the connection when the period of the package name is converted to a slash, the complete class file path c:/doc/javat/net/ Food/fruit.

A point to add, where the CLASSPATH environment variable is to take care of the class file in the package, if you care about the class file in the jar, there will be a little change, that is, you must write the actual name of the jar file in the CLASSPATH environment variable path, Instead of just specifying the directory where the jar package resides. As you can imagine, because there may be many other jar packages in the directory where the jar package is located, and the class file that we need to use will only exist in one of the jar packages, it is understood that the jar package actually acts as a primary file directory. So write the jar package file name clearly in the CLASSPATH environment variable. For example, if an 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 set up correctly, the following files can be placed under any directory:

[Java]View Plain Copy
    1. Import net.food.fruit.*;
    2. public class Libtest
    3. {
    4. public static void Main (string[] args)
    5. {
    6. Apple a=new Apple ();
    7. }
    8. }

When the compiler encounters the import statement of the fruit library, it begins to look in the directory specified by Classpath, respectively, to connect each of the root directories set in classpath with the subdirectory net/food/fruit the package name is converted to, Find the compiled file (that is, the class file) in the full directory after the connection to find the name match (Apple.class for Apple). The file was found and matched to the Apple class.

How to understand and use Java package packages

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.