Java 包(package)

包的作用、package 声明、import 导入与目录结构约定。

Beginner
Key Pointspackage 必须是源文件第一句(注释除外),且目录结构与包名一致;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.

Java
// 文件路径: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());
    }
}
Output
hello from com.example.Animal
com.example

import 关键字

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.

Java
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());
    }
}
Output
[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.

ModifierSame classSame packageSubclassOther
private✔✘✘✘
(default)✔✔✘✘
protected✔✔✔✘
public✔✔✔✔
Package names conventionally reverse the domain: com.example.project.module, all lowercase, no hyphens or underscores — those clash with directory names and tooling.

Friends & Partners