Java Packages (Package)

Source: Internet
Author: User

To better organize classes, Java provides a package mechanism for distinguishing the namespace of a class name.

the role of the package
    • 1, the function of similar or related classes or interfaces organized in the same package, convenient for the search and use of the class.

    • 2, like the folder, the package also uses the tree directory storage. The class names in the same package are different, and the names of the classes in different packages can be the same, and the package name should be distinguished when calling two classes of the same class name in different packages. Therefore, packages can avoid name collisions.

    • 3. The package also restricts access, and classes that have access to the package can access the classes in a package.

Java uses the package as a mechanism to prevent naming conflicts, access control, to provide search and locate classes (class), interfaces, enumerations (enumerations), and annotations (annotation), and so on.

The syntax format for a package statement is:

Package pkg1[. pkg2[. pkg3... ]];

For example, a Something.java file it's content

Package net. Java. Util public class Something{ ... }

Then its path should be saved by Net/java/util/something.java . Package is the role of different Java programs to save, more convenient to be called by other Java programs.

A package can be defined as a set of interconnected types (classes, interfaces, enumerations, and annotations) that provide access protection and namespace management capabilities for these types.

Here are some of the packages in Java:

    • Java.lang-Class for Package basics
    • java.io-functions that contain input and output functions

Developers can package their own set of classes and interfaces, and define their own packages. And in real-world development, it's worth advocating that when you do your own implementation of classes, grouping related classes makes it easier for other programmers to determine which classes, interfaces, enumerations, and annotations are relevant.

Because the package creates a new namespace (namespace), it does not create a naming conflict with any names in other packages. With this mechanism, it is easier to implement access control and to make locating related classes easier.

Create a Package

When creating a package, you need to give the package a proper name. After that, if the other source file contains the class, interface, enumeration, or annotation type provided by the package, the package's declaration must be placed at the beginning of the source file.

The package declaration should be in the first line of the source file, and each source file can have only one package declaration, and each of the types in the file is applied to it.

If a package declaration is not used in a source file, then the classes, functions, enumerations, comments, and so on will be placed in a nameless package (unnamed).

Example

Let's take a look at an example, which creates a package called animals. Typically, lowercase letters are used to name the class and interface names to avoid collisions.

Add an interface (interface) to the animals package:

Animal.java File Code:/*File name: Animal.java*/ package animalsinterface animal { public void eat (public void travel ("

Next, join the implementation of the interface in the same package:

Mammalint.java File Code:Package Animals;/*File name: Mammalint.java*/ Public Class Mammalint Implements Animal{ Public void Eat(){ System.Out.println("Mammal eats");} Public void Travel(){ System.Out.println("Mammal Travels");} Public Int Nooflegs(){ Return 0;} Public Static void Main(String Args[]) { mammalint m = new mammalint ( Span class= "Hl-brackets") m. Eatm. Travel} } /span>

Then, compile the two files and put them in a subdirectory called animals. Use the following command to run:

Animal.  Class  mammalint.  Class animals$ java animals/mammalintmammal eatsmammal    Travel 
Import keyword

In order to be able to use a member of a package, we need to explicitly import the package in a Java program. Use the "Import" statement to complete this function.

In the Java source file, the import statement should be located after the package statement, before all classes are defined, either without, or with multiple, syntax formats:

import package1[. Package2 ... ]. (classname|*);

If a class wants to use another class in this package in a package, the package name can be omitted.

Example

The following payroll package already contains the Employee class, and then adds a Boss class to the payroll package. The Boss class can refer to the Employee class without using the payroll prefix, as in the case of the boss class.

Boss.java File Code:Package Payroll;Public class Boss< Span class= "Hl-code" > { public void payEmployee (employee e< Span class= "Hl-brackets" >) { e. Mailcheck} } /span>

What if the Boss class is not in the payroll package? The Boss class must use one of the following methods to refer to classes in other packages.

Use the class full name description, for example:

Payroll. Employee

Introduced with the import keyword, using the wildcard character "*"

Import payroll. *;

Introduce the Employee class using the import keyword:

Import payroll. Employee;

Attention:

The class file can contain any number of import declarations. The import declaration must precede the class declaration after the package Declaration.

Directory Structure of the package

Classes are placed in a package with two main results:

    • The package name becomes part of the class name, as we discussed earlier.
    • The package name must match the directory structure in which the corresponding bytecode resides.

Here's an easy way to manage your own files in Java:

The source of the class, interface, and so on is put in a text, the name of this file is the name of this type, and with. Java as the extension. For example:

// file name: Car.java package vehicle; public class Car { // class implementation } /c14>

Next, place the source file in a directory that corresponds to the name of the package in which the class is located.

... \vehicle\Car. Java

Now, the correct class name and path will look like this:

    • Class name, vehicle. Car

    • Path name, Vehicle\car.java (in Windows system)

Typically, a company uses its Internet domain name in reverse form as its package name. For example: Internet domain name is runoob.com, all package names start with Com.runoob. Each part of the package name corresponds to a subdirectory.

For example: There is a com.runoob.test package that contains a source file called Runoob.java, so the corresponding should be like the following series of subdirectories:

.... \com\runoob\Test\runoob. Java

At compile time, the compiler creates a different output file for each class, interface, and other type defined in the package, and the output file name is the name of the type, plus the. class as the extension suffix. For example:

// file name: Runoob.java package com< Span class= "Hl-code". runoob. Testpublic class Span class= "Hl-identifier" >runoob { } class google { /span>

Now, we compile this file with the-D option, as follows:

-. Runoob.  Java   

This will put the compiled file as follows:

. \com\runoob\test\runoob.  Class.  \com\runoob\test\google.  Class      

You can import all the classes, interfaces, etc. defined in \com\runoob\test\ as follows:

Import com.  Runoob.  Test. *;     

The. class file after compilation should be the same as the. Java source file, and the directories they place should correspond to the names of the parking. However, the path to the. class file is not required to be the same as the corresponding. Java path. You can arrange the directory of source code and class.

<path-one>\sources\com\runoob\test\runoob.java<path-two>\classes\com\runoob\test\ Google.class  

In this way, you can share your class directory with other programmers without revealing your source code. Managing Source and class files in this way allows the compiler and the Java Virtual Machine (JVM) to find all the types used in your program.

The absolute path to the class directory is called class path. Set in the system variable CLASSPATH . The compiler and the Java Virtual Machine construct the path to the. class file later by adding the package name to class path.

<path-two>\classes is the class Path,package name is Com.runoob.test, and the compiler and JVM will be in <path-two>\classes\com\runoob\ Test to find the. class file.

A class path may contain several paths, and multipathing should be separated by delimiters. By default, the compiler and the JVM find the current directory. JAR files are based on classes that contain Java platforms, so their directories are placed by default in class path.

Set CLASSPATH System Variables

Use the following command to display the current CLASSPATH variable:

    • Windows platform (DOS command line):c:\> set CLASSPATH
    • UNIX platform (under Bourne shell): # echo $CLASSPATH

Delete the contents of the current CLASSPATH variable:

    • Windows platform (DOS command line):c:\> set classpath=
    • UNIX platform (under Bourne shell): # unset CLASSPATH; Export CLASSPATH

Set the CLASSPATH variable:

      • Windows platform (DOS command line): C:\> set classpath=c:\users\jack\java\classes
      • UNIX platform (under Bourne shell): # classpath=/home/jack/java/classes; Export CLASSPATH

Java Packages (Package)

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.