Java allows you to group classes in a collection called a package.

Packages are convenient for organizing your work and for separating your work from code libraries provided by others.

Package Names

The main reason for using packages is to guarantee the uniqueness of class names.

use an Internet domain name (which is known to be unique) written in reverse.

⚠️ From the point of view of the compiler, there is absolutely no relationship between nested packages. (the packages java.util and java.util.jar have nothing to do with each other.)

Class Importation

A class can use all classes from its own package and all public classes from other packages.
❓不知道前者中,本包内的private也可以访问吗?

有两种方法来使用别的包内的类,方法一是 fully qualified name: java.time.LocalDate today = java.time.LocalDate.now();

当然这太没劲了,所以第二种方法 import import java.time.* or import java.time.LocalDate

* or not

note that you can only use the * notation to import a single package. 经测验,是这个 package 中除 subpackage 外全部的 .java 文件

如果不用 *,必须精确到 .java 文件

When Name Conflict

import java.util.*; 
import java.sql.*;   // 都有 Date
import java.util.Date;  // 单独说明
 
var deadline = new java.util.Date(); 
var today = new java.sql.Date(. . .);  // 真的都要用,就只能全称了

Static Imports

A form of the import statement permits the importing of static methods and fields, not just classes.

什么意思呢?经测验,static import 聚焦于 class,旨在引进包括类在内的静态成员 (前面的普通引进聚焦于包,旨在引进包内的类)

import java.lang.Math.*   // 把所有的静态成员都引入了
import java.lang.Math.PI  // 仅引入了这个静态成员 

Add Classes into Packages

package com.horstmann.corejava;
 
public class Employee { 
	. . .
}

If you don’t put a package statement in the source file, then the classes in that source file belong to the unnamed package.

经测试,如果进入所谓的无名包,则不用 import 也可以直接调用诶。而且而且!文件路径也会发生变化:无名包是在整个项目里的,而添加包了之后,他就会去到对应包名的目录

然后是 javac 编译的时候要注意输入

Attention

The compiler does not check the directory structure when it compiles source files. For example, suppose you have a source file that starts with the directive

package com.mycompany;

You can compile the file even if it is not contained in a subdirectory com/mycompany. The source file will compile without errors if it doesn’t depend on other packages. However, the resulting program will not run unless you first move all class files to the right place. The virtual machine won’t find the classes if the packages don’t match the directories.

What if neither public nor private

就会能让整个包内的去使用,包外的用不上

但是由于包不是一个封闭的实体,我们可以在里面添加东西,这就导致了我们添加的东西触碰到了他们的内部东西,破坏了封装

The Class Path

JAR Files