Encapsulation and access control of Java (2)

Encapsulation and access control of Java (2)

Access control is the hiding of specific implementation and a part of encapsulation. Several access control modifiers mentioned earlier are part of access control. Next, we will explore another important concept, package.

Packages: library units

What problem does the package solve?

Java as an object-oriented programming language, "high cohesion and low coupling" is the goal of the design. In this case, how to achieve high cohesion and how to effectively manage these cohesive components, package plays this role. The package mechanism provides multi-layer namespaces of classes (similar to the namespace in C + +), which solves the problems of class naming conflict and class file management. It can be said that the package ensures the uniqueness of class names.

How to understand? A class library is actually a group of class files. Each file has a public class and several non-public classes, so each file has a component. Package can make these components belong to the same group.

Package statement must be the first sentence of program code except comments: package + package name. The package name format is a string of Separate lowercase English words. In order to get a unique package name, the domain name (obviously unique) is generally used as the package name in reverse order.

It is worth noting that the directory structure is implicitly specified when the package name is given.

However, it should be noted that the compiler will not check the directory structure when compiling the source file, that is, if the source file is not in the specified directory, there will be no error during compilation, but the program cannot be run because the package does not match the directory, and the virtual machine cannot find the corresponding class.

import

exceptional case:

package com.my.pac08;

import java.sql.*;
import java.util.*;

public class Tesr {
    /*Reference to'Date' is ambiguous,both
    * 'java.sql.Date'and'java.util.Date'match*/
//    Date date = new Date();
    java.sql.Date date = new java.sql.Date(6);
}

import static

package com.my.pac08;
//静态导入 java.lang.System类的静态成员变量out
import static java.lang.System.out;
//同理的,导入所有静态成员变量
//import static java.lang.System.*;
public class Test {
    public static void main(String[] args) {
    //静态导入之后,可以直接省略类名
        out.println("Hello,World!");
    }
}

Common Java packages

Common Java packages are listed below:

Reference books: Crazy Java handout, Java programming ideas, Java core technology Volume I

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>