Javase Getting Started learning 17:java Object-oriented packages (package)

Source: Internet
Author: User

a Java Bundle (package)

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

The role of the package:

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

B As with folders, packages are stored in a tree-like directory. The class names in the same package are different, and the names of the classes in different packages are

Can be the same, when calling two classes of the same class name in a different package, the package name should be distinguished. Therefore, packages can avoid name collisions.

The C 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).

The syntax format for a package statement is:

Package pkg1[. pkg2[. Pkg3 ...];

For example, a Something.java file has its contents:

<span style= "FONT-SIZE:18PX;" >package Net.java.util;public class something{     //...} </span>

Then its path should be saved by Net/java/util/something.java. The role of the package is to classify different Java programs

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 namespaces for these types

Manage the functionality.

Here are some of the packages in Java:

<span style= "FONT-SIZE:18PX;" >1) Java.lang Package: Java's core class library, contains the necessary system classes to run Java programs, such as basic data types, basic mathematical functions, string processing, threading, exception handling classes, the system defaults to load this package. 2) java.io Package: Java language standard input/output class library, such as basic input/output stream, file input/output, filter input/output stream, etc. 3) Java.util Package: Contains a date class such as processing time, a vector class that is processed into an array, and a stack and a Hashtable class. 4) java.awt Package: Building a graphical user interface (GUI) class library, low-level drawing operations graphics class, graphical interface components and layout management such as the CheckBox class, Container class, Layoutmanger interface, and interface user interaction control and event response, such as the event class. 5) Java.awt.image Package: the Java Tool Class library that handles and manipulates images from the web. 6) Java.wat.peer package: Rarely used directly in the program, making the same Java program run on different hardware and software platforms. 7) Java.applet package. 8) java.net Package: The class library that realizes network function has socket class, ServerSocket class. 9) Java.corba package and Java.corba.orb bag. Java.lang.reflect Package: Provides tools for reflecting objects. One) Java.util.zip package: To achieve the file compression function. Java.awt.datatransfer Package: A tool class that handles data transfer, including the Clipboard, string sender, and so on. ) java.awt.event package. java.sql Package: Implements the JDBC Class library. JAVA.RMI provides remote connection and onboarding support. Java.security provides security-related support. </span>

Developers can package their own set of classes and interfaces, and define their own packages. And in practical development this is worth advocating when you

After you have completed the implementation of your class, grouping related classes makes it easier for other programmers to determine which classes, interfaces, enumerations, and annotations are related

Of

Because the package creates a new namespace (namespace), it does not create a naming conflict with any name in the other package. Using the Package this

Mechanisms to make access control easier and easier to locate related classes.

Two Creating a package

When creating a package, you need to give the package a proper name. After that, if the other source file contains the package

Class, interface, enumeration, or annotation type, the package 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 source

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

Instance:

Let's take a look at an example, which creates a package called animals. Usually use lowercase letters to name the class, the interface name, and the

Conflict.

Add an interface (interface) to the animals package:
<span style= "FONT-SIZE:18PX;" >/* file name: Animal.java */package animals;interface Animal {public   void eat ();   public void travel (); </span>
Next, join the implementation of the interface in the same package:
<span style= "FONT-SIZE:18PX;" >/* file name: Mammal.java */package animals;public class mammal implements animal{public   void Eat () {      SYSTEM.OUT.P Rintln ("Mammal Eats");   }   public void Travel () {      System.out.println ("Mammal Travels");    public int Nooflegs () {      return 0;   }} </span>

Then, compile these two files:


Post-Compiled directory:


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


Three Import Keywords

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, the definition of all classes can not, or can have more than one, its syntax format

As: Import Package1[.package2 ...]. (classname|*);

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

Instance:

The following payroll package already contains the employee class, and then adds a boss class to the payroll package. When the Boss class refers to the employee class

Instead of using the payroll prefix, the Boss class has the following examples:

<span style= "FONT-SIZE:18PX;" >package Payroll;public class boss{public   void Payemployee (Employee e) {      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:

1) Use the class full name description, for example:

Payroll. Employee

2) Use the Import keyword to use the wildcard character (*)

Import payroll.*;

3) Introducing the employee class with 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.

Let's go on to see that instance in the process of creating the package:

We will then create a Test.java source file in the source file directory:

<span style= "FONT-SIZE:18PX;" >import animals.*;p ublic class test{public   static void Main (string[] args) {      mammal m=new mammal ();      M.eat ();      M.travel ();   }} </span>
compiling this class has the following problems:


This requires that we delete or re-move the two source files that created the animals package to another folder, and I put it under the source folder:


Compile the Test.java source file and run the bytecode file again:


Four directory structure of the package

Classes are placed in a package with two main results:

A package name becomes part of the class name, as we discussed earlier.

The B 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:

<span style= "FONT-SIZE:18PX;" >//filename:  car.javapackage vehicle;public class Car {   //class implementation  }</span>

Next, put the source file in a directory, the directory to correspond to the name of the package class: .... \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)

Typically, a company uses its Internet domain name in reverse form as its package name. For example: Internet domain name is apple.com, all package names are

Com.apple begins. Each part of the package name corresponds to a subdirectory.

For example: This company has a com.apple.computers package, which contains a source file called Dell.java, then the corresponding, should have

As in the following series of subdirectories: .... \com\apple\computers\dell.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 this class

Name, plus the. class as the extension suffix. For example:

<span style= "FONT-SIZE:18PX;" >//file name: Dell.javapackage com.apple.computers;public class dell{//}class ups{//}</span>      

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

Javac-d. Dell.java

This will put the compiled file as follows:

. \com\apple\computers\dell.class

. \com\apple\computers\ups.class

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

Import com.apple.computers.*;

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. class is not required.

The path to the file is the same as the corresponding. Java path. You can arrange the directory of source code and class.

<path-one>\sources\com\apple\computers\dell.java

<path-two>\Classes\com\apple\computers\dell.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 can

Let the compiler and the Java Virtual Machine (JVM) 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. Compiler and Java Virtual machine by adding the package name to the

The path to the. class file is later constructed into class path.

<path-two>\classes is class path, The package name is Com.apple.computers, and the compiler and JVM will be in <path-

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

A class path may contain several paths. Multipath 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.

Five set classpath system variables

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

Windows platform (DOS command line), c:\> set CLASSPATH

UNIX platform (Bourne shell),% echo $CLASSPATH

2) Delete the contents of the current CLASSPATH variable:

Windows platform (DOS command line), c:\> set classpath=

UNIX platform (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 (Bourne shell),% classpath=/home/jack/java/classes; Export CLASSPATH

The understanding of the package is these now, some places still do not understand, need to gradually deepen the understanding of Java package in the future practice. The wrong place

Please point out.


Javase Getting Started learning 17:java Object-oriented packages (package)

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.