跳到内容

元数据卡

  • 前置知识:第7章(中)——封装
  • 预计时间:12 分钟
  • 完成标志:理解 static 字段和方法属于类而非对象,能区分静态与实例成员

一个计数器放在哪?

"总共有多少本书被创建过"——这个计数不能放在单个 Book 对象上。老陈说:"有些东西属于整个类。用 static。"

java
class Book {
    String title;
    static int totalCount = 0;  // 所有对象共享一份

    Book(String title, String author) {
        this.title = title;
        this.author = author;
        totalCount++;
    }
}
public class Library {
    public static void main(String[] args) {
        new Book("Java 核心技术", "Horstmann");
        new Book("深入理解计算机系统", "Bryant");
        new Book("设计模式", "GoF");
        System.out.println("已创建图书:" + Book.totalCount);  // 3
    }
}

语言:Java 预期输出已创建图书:3关键理解totalCount 内存里只有一份。推荐通过 类名.静态字段 访问。

静态方法

不依赖任何对象状态的方法——无需 new,直接 类名.方法() 调用:

java
class MathUtils {
    static int max(int a, int b) { return a > b ? a : b; }
}
public class Main {
    public static void main(String[] args) {
        System.out.println(MathUtils.max(10, 20));  // 20
    }
}

预期输出20

static 核心规则

  1. 静态方法只能访问静态字段/方法——不能直接访问实例成员
  2. 实例方法可以访问所有——静态的和非静态的都可以
  3. 静态方法中没有 this——它不属于任何对象

为什么 main 必须是 static?程序启动时没有任何对象。

java
public class Main {
    String greeting = "Hello";
    public static void main(String[] args) {
        System.out.println(greeting);  // ❌ 编译错误
        Main m = new Main();
        System.out.println(m.greeting);  // ✅ Hello
    }
}

工具类模式

Math.max()Arrays.sort() 都是静态方法。这类类叫工具类,通常私有化构造方法防实例化:

java
class MathUtils {
    private MathUtils() {}  // 禁止 new
    public static int max(int a, int b) { return a > b ? a : b; }
    public static int min(int a, int b) { return a < b ? a : b; }
}

什么时候用 static?

  1. 方法只依赖参数(工具方法)
  2. 常量(static final
  3. 计数器(所有对象共享一个数)
  4. main 方法——JVM 启动入口

差异窗口:C++ 与 Python

C++ 静态成员变量必须在类外单独定义:

cpp
class MathUtils {
    static int counter;  // 声明
};
int MathUtils::counter = 0;  // 定义——分配存储

Python@staticmethod

python
class Book:
    total_count = 0
    def __init__(self, title):
        self.title = title
        Book.total_count += 1
    @staticmethod
    def get_count():
        return Book.total_count

下一步

现在你学会了定义完整的类。但实际写代码时有很多陷阱——引用赋值、值传递……

下一节:OOP 练习与常见陷阱ch07-lab-oop.md

Built with VitePress | Software Systems Atlas