☰ 总览更新 10-12 22:33

08 · static

我的原话

一句话

有 static = 属于类,全体一份,用类名调;没 static = 属于每个对象,先 new 再用对象调。

判断法:方法里用没用「某个人自己的东西」

class User {
    String name;
    static int count = 0;
    User(String n) { name = n; count++; }

    void sayHi() { System.out.println("我叫" + name); }          // 用了「我的」name → 不加 static
    static void howMany() { System.out.println("一共有 " + count + " 个人"); }  // 只看墙上计数板 → 可 static
}
User.howMany();            // 一共有 0 个人(一个人都没 new 也能问)
User a = new User("张三");
a.sayHi();                 // 我叫张三
User.sayHi();              // ❌ 无法从静态上下文中引用非静态 方法 sayHi() —— 没说让「谁」说

比喻:班级。名字各人一个(非 static);墙上计数板全班一块(static)。

为什么 main 必须 static

程序刚启动时仓库是空的,一个对象都没有 → JVM 只能用「类名.main()」叫它

报错「无法从静态上下文中引用非静态 方法 xxx()」

static 的 main 里直接调非 static 方法 = 广播喊「说话!」但教室里没人。修法:先 new 一个对象,再 对象.方法()

题

题 我答 结果
两个对象,static count,打印 a.count 2 ✅
删掉 static 1 ✅(每人自己一块,真跑过 T14)
User.howMany() 和 User.sayHi() 哪个报错 第二个 ✅

真跑过:T11、T15.java、t8/T12、T13、T14