看板 java 關於我們 聯絡資訊
小弟寫了一個程式如下 public class test { private int count; //計數器用 public int addCount(){ count++; return count; } public test(){ System.out.println("new test"); count=0; } public static void main(String[] args) { test1 t1 = new test1(); test2 t2 = new test2(); System.out.println(t1.addCount()); System.out.println(t2.addCount()); } } //另外有兩個class繼承test public class test1 extends test { public test1(){ System.out.println("new test1"); } } public class test2 extends test{ public test2(){ System.out.println("new test2"); } } 而最後印出的結果 : new test new test1 new test new test2 1 1 可是我想要兩個使用相同的計數器 也就是會印出 1 2 不知除了把count 改成 static外 有別的方法嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.180.196
MouthBoom:GOOD QUESTION 02/28 15:09
luoqr:why not static? 02/28 15:14
tkcn:目前這種情況我也覺得 static 就夠了, 02/28 15:16
tkcn:不過也許你想要的是 Singleton (但最後還是用了 static 呀..) 02/28 15:19
AmosYang:有 :) 02/28 15:20
tkcn:噢...自己提供 Counter 物件進去似乎才是你想要的? 02/28 15:20
sinner0116:想知道有沒除了使用static外其他的方法 02/28 15:25
AmosYang:有 :) 02/28 15:27
tkcn:你知道constructor可傳參數進去嗎?這樣不就是share instance? 02/28 15:27
puppy8224:static是殺小 我只知道dynamic 02/28 15:50
sinner0116:嗯嗯 不過這樣new的時候有點麻煩 02/28 15:50
AmosYang:麻煩?那就抄起JVMTI硬上吧; Singleton is for noobs XD 02/28 16:01
TonyQ:為什麼有static不用要找別的方法 @_@ 02/28 16:55
qrtt1:無論用static或Counter物件,都需再考慮thread-safe 02/28 20:11