Java 包(package)
包的作用、package 声明、import 导入与目录结构约定。
创建包
Packages prevent name clashes and define access boundaries. After package com.example; the file must live in com/example/, or the runtime will not find the class.
// 文件路径:com/example/Animal.java
package com.example;
public class Animal {
public void hello() {
System.out.println("hello from com.example.Animal");
}
public static void main(String[] args) {
new Animal().hello();
System.out.println(Animal.class.getPackageName());
}
}hello from com.example.Animal
com.exampleimport 关键字
import saves you from writing fully qualified names: import java.util.List; for one class, import java.util.*; for a package (subpackages excluded). java.lang is imported automatically.
import java.util.ArrayList;
import java.util.List;
public class ImportDemo {
public static void main() {
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
System.out.println(list);
System.out.println(list.getClass().getSimpleName());
System.out.println(String.class.getPackageName());
}
}[a]
ArrayList
java.lang包的访问权限
Members without a modifier are package-private: visible only inside the package. protected additionally allows subclasses in other packages. That is what makes a package a module boundary.
| Modifier | Same class | Same package | Subclass | Other |
|---|---|---|---|---|
| private | ✔ | ✘ | ✘ | ✘ |
| (default) | ✔ | ✔ | ✘ | ✘ |
| protected | ✔ | ✔ | ✔ | ✘ |
| public | ✔ | ✔ | ✔ | ✔ |
com.example.project.module, all lowercase, no hyphens or underscores — those clash with directory names and tooling.创建包
包用来避免类名冲突并划分访问边界。声明 package com.example; 后,源文件必须放在 com/example/ 目录下,否则运行时会找不到类。
// 文件路径:com/example/Animal.java
package com.example;
public class Animal {
public void hello() {
System.out.println("hello from com.example.Animal");
}
public static void main(String[] args) {
new Animal().hello();
System.out.println(Animal.class.getPackageName());
}
}hello from com.example.Animal
com.exampleimport 关键字
import 让你不必写全限定名。import java.util.List; 导入单个类,import java.util.*; 导入整个包(不含子包)。java.lang 自动导入,无需声明。
import java.util.ArrayList;
import java.util.List;
public class ImportDemo {
public static void main() {
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
System.out.println(list);
System.out.println(list.getClass().getSimpleName());
System.out.println(String.class.getPackageName());
}
}[a]
ArrayList
java.lang包的访问权限
不加访问修饰符的成员是「包级私有」,只有同一个包内的类能访问。protected 则允许子类(即使在不同包)访问。这是包作为「模块边界」的意义。
| 修饰符 | 同类 | 同包 | 子类 | 其他 |
|---|---|---|---|---|
| private | ✔ | ✘ | ✘ | ✘ |
| (默认) | ✔ | ✔ | ✘ | ✘ |
| protected | ✔ | ✔ | ✔ | ✘ |
| public | ✔ | ✔ | ✔ | ✔ |
com.example.project.module。全小写、不要用连字符或下划线,否则与目录名和工具链容易冲突。