class A {
private static int cnt = 0;
public void f() { cnt++; }
static int out(int i) { return cnt; }
}
public class Main {
public static void main(String[] args) {
A aa1 = new A();
A aa2 = new A();
System.out.println(A.out(1)); // 輸出 2
}
}
提問者認為 new A() 應自動調用無參構造器並執行 f() 導致計數增加,實際上構造器默認不調用 f(),且代碼邏輯本身無誤。
在 Eclipse (Mars) 中直接運行上述代碼,控制台正常輸出 2。說明:
cnt 屬於類,兩次 new A() 不會重置。f() 時 cnt 仍為 0,但示例中 out(1) 直接返回 cnt,輸出 0 才符合邏輯。提問者可能誤以為構造器會自動調用 f()。f()。用static輸出對象的個數)雖合法但不規範,建議改為英文。 class Counter {
private static int count = 0;
public Counter() { count++; } // 構造器中計數
public static int getCount() { return count; }
}
public class Demo {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.getCount()); // 2
}
}