Re: [問題] 求助inner class
※ 引述《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
03/13 00:33, 1F
推
03/13 00:36, , 2F
03/13 00:36, 2F
※ 編輯: eieio 來自: 207.171.191.60 (03/13 02:30)
討論串 (同標題文章)