Java object-oriented package (package)

Source: Internet
Author: User

Java object-oriented package (package)
A Java package)

To better organize classes, Java provides a package mechanism to differentiate the namespace of class names.

The role of the package:

A organizes similar or related classes or interfaces in the same package to facilitate the search and use of classes.

B. Like folders, packages are stored in a tree directory. The class names in the same package are different. The class names in different packages are

It can be the same. When two classes with the same name in different packages are called at the same time, the package name should be added. Therefore, the package name conflict can be avoided.

Package C also limits access permissions. Only classes with package access permissions can access the classes in a package.

Java uses the package mechanism to prevent naming conflicts and access control, and provides search and locating classes, interfaces, and enumeration.

(Enumerations) and annotations (annotation.

The syntax format of the package statement is:

Package pkg1 [. pkg2 [. pkg3…];

For example, the content of a Something. java file:

 

package net.java.util;public class Something{     //...}

 

The path should be saved as net/java/util/Something. java. Package is used to classify different java programs

To be conveniently called by other java programs.

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

Management function.

The following are some Java packages:

1) java. lang package: the Core class library of java, including the System Classes essential for running java programs, such as basic data types, basic mathematical functions, string processing, threads, and exception handling classes, the system loads this package by default. 2) java. io package: standard input/output class library of java language, such as basic input/output stream, file input/output, and filter input/output stream. 3) java. util package: contains the date class for processing time, the Vector class for processing to an array, and the stack and HashTable classes. 4) java. awt package: Class Library for building a graphical user interface (GUI), Graphics class for low-level drawing operations, graphical interface components and layout management, such as Checkbox class, Container class, And LayoutManger interface, interface user interaction control and Event response, such as the Event class. 5) java. awt. image package: java tool library for processing and manipulating images from the Internet. 6) java. wat. peer package: it is rarely used directly in programs, so that the same java program runs on different software and hardware platforms. 7) java. applet package. 8) java.net package: class libraries that implement network functions include Socket and ServerSocket. 9) java. corba package and java. corba. orb package. 10) java. lang. reflect package: provides tools for reflecting objects. 11w.java.util.zip package: Implements File compression. 12) java. awt. datatransfer package: tool class for processing data transmission, including clipboard and string transmitter. 13) java. awt. event package. 14) java. SQL package: implements the JDBC class library. 15) java. rmi supports remote connection and loading. 16) java. security provides security support.

Developers can package a group of classes and interfaces and define their own packages. It is also worth advocating in actual development.

After completing the class implementation, You can group related classes so that other programmers can easily determine which classes, interfaces, enumeration and comments are related.

.

Because the package creates a new namespace, it does not conflict with any name in other packages. Use the package

And makes it easier to implement access control and to locate related classes.

2. Create a package

When creating a package, you need to give it a proper name. If another source file contains the package

When providing classes, interfaces, enumerations, or annotation types, the package declaration must start with the source file.

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

If the package declaration is not used in the file, the classes, functions, enumeration, and comments in the package will be placed in an unnamed package.

Instance:

Let's take an example. This example creates a package called animals. Generally, lower-case letters are used for naming.

Conflict.

Add an interface to the animals package ):
/* File name: Animal. java */package animals; interface Animal {public void eat (); public void travel ();}
Next, add the implementation of this interface to the same package:
/* File name: Mammal. java */package animals; public class Mammal implements Animal {public void eat () {System. out. println ("Mammal eats");} public void travel () {System. out. println ("Mammal travels");} public int noOfLegs () {return 0 ;}}

Then, compile the two files:

Compiled directory:

The bytecode file (class file) in the animals package ):

Three import keywords

To be able to use members of a package, we need to explicitly import the package in the Java program. You can use the "import" statement to complete this function.

In the java source file, the import statement should be placed after the package statement. Before the definition of all classes, there may be no or multiple, and its syntax format

Is: import package1 [. package2…]. (Classname | *);

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

Instance:

The following payroll package already contains the Employee class. Next, add a Boss class to the payroll package. When the Boss class references the Employee class

You do not need to use the payroll prefix. The Boss class instance is as follows:

package payroll;public class Boss{   public void payEmployee(Employee e){      e.mailCheck();   }}

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

1) use the full name of the class, for example:

Payroll. Employee

2) import with the import keyword and use the wildcard (*)

Import payroll .*;

3) use the import keyword to introduce the Employee class

Import payroll. Employee;

Note:

Class files can contain any number of import declarations. The import declaration must be completed after the package declaration and before the class declaration.

Let's continue to look at the instance during the package creation process:

Create a Test. java source file in the directory of the source file:

import animals.*;public class Test{   public static void main(String[] args){      Mammal m=new Mammal();      m.eat();      m.travel();   }}
Compiling this class has the following problems:

In this case, we need to delete the two source files that created the animals package or move them to another folder. I put it in the source folder:

Re-compile the Test. java source file and run the bytecode file:

4. package directory structure

The class has two main results in the package:

Package A is A part of the class name, as we discussed earlier.

The Package B name must be consistent with the directory structure of the corresponding bytecode.

Below is a simple way to manage your own java files:

Put the source code of classes and interfaces in a text file. The file name is the name of this type and uses. java as the extension. For example:

// File name: Car. javapackage vehicle; public class Car {// class Implementation}

Next, put the source file in a directory. The directory should be the name of the package where 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)

Generally, a company uses the reverse form of its Internet domain name as its package name. For example, the Internet domain name is apple.com, and all the package names are

Com. apple. Each part of the package name corresponds to a sub-directory.

For example, the company has a com. apple. computers package that contains a source file called Dell. java.

A series of subdirectories are as follows:... \ com \ apple \ computers \ Dell. java

During compilation, the compiler creates a different output file for each class, interface, and Other types defined in the package. The name of the output file is the class.

Type name, and Add. class as the extension suffix. For example:

// File name: Dell. javapackage com. apple. computers; public class Dell {//} class Ups {//}

Now we use the-d option to compile this file, as shown below:

Javac-d. Dell. java

The compiled files will be placed as follows:

. \ Com \ apple \ computers \ Dell. class

. \ Com \ apple \ computers \ Ups. class

You can import all classes and interfaces defined in \ com \ apple \ computers \ as follows:

Import com. apple. computers .*;

The compiled. class files should be the same as the. java source files, and their directory should correspond to the package name. However,. class is not required.

The file path is the same as the corresponding. java path. You can separate source code and class directories.

\ Sources \ com \ apple \ computers \ Dell. java

\ Classes \ com \ apple \ computers \ Dell. class

In this way, you can share your class directories with other programmers without disclosing your source code. You can use this method to manage source code and class files.

Let the compiler and Java Virtual Machine (JVM) Find all types used in your program.

The absolute path of the class directory is called class path. In the CLASSPATH system variable. The compiler and Java Virtual Machine Add the package name

To the class path and then construct the path of the. class file.

\ Classes is the class path, and the package name is com. apple. computers, while the compiler and JVM will < p=""> <>

Find the. class file in two> \ classes \ com \ apple \ compters.

A class path may contain several paths. Multiple paths should be separated by separators. By default, the compiler and JVM search for the current directory.

JAR files include classes related to the Java platform, so their directories are stored in the class path by default.

5. Set CLASSPATH System Variables

1) use the following command to display the current CLASSPATH variable:

Windows (DOS command line)-> C: \> set CLASSPATH

UNIX platform (under the Bourne shell)-> % echo $ CLASSPATH

2) Delete the content of the current CLASSPATH variable:

Windows platform (DOS command line)-> C: \> set CLASSPATH =

UNIX platform (under the Bourne shell)-> % unset CLASSPATH; export CLASSPATH

3) set the CLASSPATH variable:

Windows platform (DOS command line)-> set CLASSPATH = C: \ users \ jack \ java \ classes

UNIX platform (under the Bourne shell)-> % CLASSPATH =/home/jack/java/classes; exportCLASSPATH

This is the current understanding of the package. In some cases, I still don't quite understand it. I need to gradually deepen my understanding of the Java package in future practices. Incorrect location

Please note.

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.