Re: [問題] 求助inner class

看板java作者 (好多目標)時間13年前 (2012/03/13 00:31), 編輯推噓2(200)
留言2則, 1人參與, 最新討論串2/2 (看更多)
※ 引述《soso0316 (carl)》之銘言: : 會有錯誤:No enclosing instance of type test is accessible. Must qualify the allocation : with an enclosing instance of type test (e.g. x.new A() where x is an : instance of test). 這個錯誤的原型長這樣: public class Test { private String key; public String getKey() { return key; } public static String getKey() { return key; // 這裡會錯 } ... } 上面這段 code,key 必須經過 new Test() 才會存在,可能一個都沒有,也可 能很多個。但是 static method 則是一直都存在,而且是所有 Test 都共用的 ,自然不能有拿到 key 的權限。但如果上面的 key 改成 private static String key; 那麼錯誤就沒了,只是所有的 Test 都必須用相同的一個 key。 Inner class 也就是一個 variable,有 static 和 non-static 之分。原始的 code 裡面,main() 是 static method,所以 inner class 也必須是 static。 其實在大部份的情況下,inner class 都應該要是 static。 (看了推文自己加註) 應該說,如果這個 inner class 理論上可以另外開一個 class 放在另一個檔 ,但是因為用途跟現在的 class 緊密結合而應該寫在一起,那就應該用 static 。 -- Just because you deserve this doesn't mean they're gonna give it to you. Sometimes you gotta take what's yours. ── Kenny Ray Carter -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 207.171.191.60

03/13 00:33, , 1F
說inner class 都應該要是 static好像怪怪的吧....
03/13 00:33, 1F

03/13 00:36, , 2F
是寫程式的習慣問題嗎?這樣好像把calss當namespace用
03/13 00:36, 2F
※ 編輯: eieio 來自: 207.171.191.60 (03/13 02:30)
文章代碼(AID): #1FNYJapq (java)
討論串 (同標題文章)
文章代碼(AID): #1FNYJapq (java)