The thinking Logic of computer program (22)-The organization mechanism of code

Source: Internet
Author: User

There is a similar problem with programming in any language, that is, how to organize the code, specifically, how to avoid naming conflicts? How to reasonably organize various source files? How do I use a third-party library? How do the various code and dependent libraries compile the connection as a complete program?

This section discusses the solution mechanisms in Java, including packages, jar packages, program compilation and connection, starting with the package.

Concept of the Package

Programming in any language has the same problem, that is, naming conflicts , programs are not generally written by a person, will invoke the system-provided code, the code in a third-party library, code written by other people in the project, different people may define the same class name/interface name for different purposes, The way to solve this problem in Java is the package .

Even though the code is written by one person, it is not easy to understand and maintain a number of classes and interfaces that are not very relational, and the way to organize classes and interfaces in Java is also a package.

The package is a relatively easy to understand concept, similar to the folder in the computer, as we manage the files in the computer, the file in the folder, the class and interface in the package, for easy organization, the folder is generally a hierarchy, package is similar.

The package has a package name, which is a comma-delimited representation of the hierarchy. For example, we used to use the String class, is located under the package Java.lang, where Java is the upper package name, Lang is the lower package name, with the full package name of the class name is its fully qualified name , For example, the fully qualified name of the String class is java.lang.String. All classes and interfaces in the Java API are located under package Java or Javax, Java is a standard package, and javax is an extension package.

Next, we discuss the details of the package, starting with the package where the Declaration class resides.

Declare the package where the class resides

Grammar

We did not define the package when we defined the class, and by default the class is under the default package, and using the default package is not recommended, and the default package in the article is simply for simplicity.

When defining a class, you should first declare its package name using the keyword packages, as follows:

 Package Shuo.laoma;  Public class Hello {    // definition of Class }

The package name of the above declaration class Hello is Shuo.laoma, and the package declaration statement should be at the front of the source code, preceded by a statement other than the comment.

The package name and file directory structure must match , if the source file root directory is E:\src\, then the above Hello class corresponding file Hello.java, its full path should be E:\src\shuo\laoma\Hello.java. If they do not match, Java will prompt a compilation error.

Naming conflicts

To avoid naming conflicts, one of the conventions for naming package names in Java is to use a domain name as a prefix because the domain name is unique and typically defines the package name in terms of the reverse order of the domain name, for example, the domain name is: apache.org, and the package name begins with Org.apache.

No domain name, it does not matter, use a other code is not very likely to use the package name, such as the "Shuo.laoma" used in this article, "Old horse said programming" example.

If the code needs to be exposed to someone else, it is best to have a domain name to ensure uniqueness, and if it is used internally, make sure that no other code inside uses the package name.

Organization Code

In addition to avoid naming conflicts, the package is also a convenient mechanism for organizing code, in general, all the code under the same project has an identical package prefix, the prefix is unique, not the same name as other code, within the project, according to different purposes subdivided into sub-packages, the child package may be divided into sub-packages, to form a hierarchy, Internal implementations are typically located in the lower-level package.

The package can be easily modularized, different functions can be located in different packages, different developers are responsible for different packages. packages can also be easily encapsulated, and classes for external use can be placed on top of the package, while internal implementation details can be placed in the lower sub-package.

Using Classes with Packages
References to classes under the same package do not require a package name and can be used directly. However, if the class is not within the same package, you must know which package it is in, in two ways, one through the fully qualified name of the class, and the other to introduce the used class to the current class.

With one exception, classes under the Java.lang package can be used directly, without introduction, and without the use of fully qualified names, such as the string class, the system class, and other classes within the package.

For example, using the sort method in the arrays class, with a fully qualified name, can be used:

int New int []{1,4,2,3};java.util.arrays.sort (arr); System.out.println (java.util.Arrays.toString (arr));

Obviously, this is more verbose, the other is to introduce the class into the current class, the introduction of the keyword is import, import needs to be placed after the package definition, before the class definition, as follows:

 package   Shuo.laoma;  import   Java.util.Arrays;  public  class   Hello { public  static  void   main (string[] args) {int  [] arr = new  int         []{1,4,2,3};        Arrays.sort (arr);    System.out.println (arrays.tostring (arr)); }}

Import, you can introduce all classes under a package at once, and the syntax is to use. *, for example, the introduction of all classes under the Java.util package, the syntax is: Import java.util.*, it should be noted that this introduction is not recursive, It only introduces the direct class under the Java.util package, without introducing the classes within the nested package java.util, for example, the class below the package java.util.zip is not introduced. Attempts to nest the introduced form are also invalid, such as import java.util.*.*.

Within a class, references to other classes must be uniquely deterministic, cannot have a class with duplicate names, and, if so, only one of the classes can be introduced through import, and other classes with the same name must use fully qualified names.

Introducing classes is a tedious task, but most Java development environments provide tools to do this automatically, such as in Eclipse, through the menu "Source->organize Imports" or corresponding shortcut keys ctrl+shift+ o The introduction class can be automatically managed.

Package Scope Visibility

As we have described in the previous sections, for classes, variables, and methods, you can have a visibility modifier, public/private/protected, and the previous section, we mentioned that you can not write modifiers. If any modifier is not written, its visibility range is within the same package, other classes within the same package can be accessed, and classes within other packages are not accessible.

It is necessary to note that the same package refers to the same direct package, the class under the sub-package is not accessible, for example, Classes Shuo.laoma.Hello and Shuo.laoma.inner.Test, where the package Shuo.laoma and Shuo.laoma.inner are two completely separate packages, and have no logical connection, the Hello class and the Test class cannot access each other's package visibility methods and genera Of

In addition, it is necessary to note that the protected modifier,protected visibility includes package visibility, that is , declared as protected, which not only indicates that subclasses are accessible, but also that other classes within the same package can be accessed, even if these classes are not subclasses.

In summary, the visibility range from small to large is:

Private < Default (package) < protected < public

Jar Package

In order to facilitate the use of third-party code, but also for the convenience of the code we write to other people, a variety of programming languages have the concept of packaging, packaging is generally not the source code, but the compiled code, packaging will be a number of compiled files packaged as a file, convenient for other programs to call.

In Java, the Java class file for one or more of the compiled packages can be packaged as a file, and the packaged command in Java is a jar, and the packaged file suffix is. jar, commonly referred to as a jar package.

You can package it in the following way, first to the compiled Java class file root, and then run the following command to package:

JAR-CVF < package name >.jar < top package name >

For example, to package the class described earlier, if Hello.class is located in E:\bin\shuo\laoma\Hello.class, you can go to the directory E:\bin, and then run:

JAR-CVF Hello.jar Shuo

Hello.jar is a jar package, which is actually a compressed file that can be opened using the Unzip tool.

Java class libraries, third-party class libraries are provided as jar packages. How do I use jar packages? Add it to the classpath (classpath) . What is a classpath?

Compilation and connection of programs

From the Java source code to the running program, there are two steps to compile and connect. Compiling is the source code file into a byte code, suffix is. class file, this work is usually done by javac this command. The connection is executed dynamically at runtime, the. class file cannot be run directly, the Java virtual machine is running, the virtual machine sounds abstract, the Java command is executed, This command parses the. class file, transforms it into a machine-recognized binary code, and then runs the so-called connection that loads the corresponding bytecode and executes according to the referenced class.

Java compile and run, you need to specify a classpath with parameters, that is, the classpath. The classpath can have multiple, for the direct class file, the path is the root of the class file, for the jar package, the path is the full name of the jar package (including the path and the jar package name), in the Windows system, multiple paths with semicolons, delimited, and in other systems, colon: delimited.

when Java source code is compiled, the Java compiler determines the fully qualified name of each class referenced , determined by the import statement and classpath. If the import is a fully qualified class name, you can compare and determine it directly. If it is a fuzzy import (import with. *), then find the corresponding parent package according to Classpath, and then look for the corresponding class under the parent package. If more than one fuzzy import package has the same class name, Java prompts for a compilation error, which should explicitly specify which class to import.

In the Java runtime, the class is found and loaded according to the fully qualified name of the class, looking for it in the classpath, and if it is the root of the class file, directly to see if there are subdirectories and files, and if it is a jar file, first extract the files in memory and then see if there are any corresponding classes.

In summary,Import is a compile-time concept that determines the fully qualified name that, at run time, finds and loads the class based solely on the fully qualified name, and both the compilation and runtime depend on the classpath, and the jar files in the classpath are decompressed for finding and loading classes.

Summary

This section describes the mechanisms of code organization in Java, packages and jar packages, and the compilation and connection of programs. Placing classes and interfaces within the appropriate hierarchy of packages, avoiding naming conflicts, making code clearer, facilitating encapsulation and modular development, using third-party code with jar packages, and packaging your own code as a jar package for use by other programs is necessary to solve complex problems.

We have been saying that the program is mainly about the operation of data, to represent and manipulate the data, we introduce the basic types, classes and interfaces, the following section, we introduce the Java in the representation and operation of a special kind of data mechanism- enumeration.

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Write attentively, original articles, and keep all copyrights.

-----------

More related original articles

Thinking Logic of computer programs (21)-The nature of inner classes

Thinking Logic of computer programs (20)-Why abstract classes?

The thinking Logic of computer program (19)-The nature of the interface

Logic of the computer program (18)-Why inheritance is a double-edged sword.

The thinking Logic of computer program (17)-The basic principle of inheriting implementation

Logic of the computer program (16)-Details of the inheritance

Thinking Logic of computer program (15)-Initial knowledge inheritance and polymorphism

Logic of the computer program (14)-a combination of classes

Thinking Logic of computer program (13)-Class

The thinking Logic of computer program (22)-The organization mechanism of code

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.