Re: [問題] JAVA如何設定全域變數

看板java作者 (c'est la vie)時間17年前 (2006/10/16 14:33), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串8/9 (看更多)
假設需求是讓兩個類別的實體能一起使用同一個變數 由於基本型別無法做到call by reference, 所以使用wrapper 個人覺得在非多執行緒的情況下 實在能不用static變數就不要用 在main function中定義一個變數其實就夠用了, 不是嗎? 我覺得比較安全的做法如下 public class Class1 { public Class1(MyInt integer) { this.integer = integer; this.integer.setInteger(100); } private final MyInt integer; public static void main(String[] args) { final MyInt integer = new MyInt(0); Class1 c1 = new Class1(integer); Class2 c2 = new Class2(integer); } } class Class2 { public Class2(MyInt integer) { this.integer = integer; this.integer.setInteger(200); } private final MyInt integer; } class MyInt { public MyInt(int integer) { this.integer = integer; } private int integer; public int getInteger() { return integer; } public void setInteger(int integer) { this.integer = integer; } } ※ 引述《nelsonsnp.bbs@bbs.wretch.cc (暑假作業真多..泣)》之銘言: : 全域變數應該第一個想到的是static吧, : class B { : static int i=0; : } : public class A{ : public static void main(String[] args){ : B.i = +2; : System.out.println(B.i); : } : } : 這樣是不是也可行呢,而且static variable是放在記憶體中Global的區塊喔 : ※ 引述《qrtt1.bbs@bbs.sayya.org (foolish)》之銘言: : > 目標雖然達成了。但這實在是一個bad style -- And I don't think that I'll see her again, But we shared a moment that will last till the end. You're beautiful. You're beautiful. You're beautiful, it's true. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.197.139 ※ 編輯: webberhan 來自: 220.130.197.139 (10/16 14:46) ※ 編輯: webberhan 來自: 220.130.197.139 (10/16 14:51)
文章代碼(AID): #15CoV0ei (java)
討論串 (同標題文章)
文章代碼(AID): #15CoV0ei (java)