作者eieio (好多目标)
看板java
标题Re: [问题] 求助inner class
时间Tue Mar 13 00:31:29 2012
※ 引述《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
1F:推 LaPass:说inner class 都应该要是 static好像怪怪的吧.... 03/13 00:33
2F:推 LaPass:是写程式的习惯问题吗?这样好像把calss当namespace用 03/13 00:36
※ 编辑: eieio 来自: 207.171.191.60 (03/13 02:30)