標籤:
這種情況一般發生在“在靜態方法裡面使用內部類”
測試代碼:
public class Test {public static void main(String[] args) {A a = new A(1);}class A {int x;public A() {}public A(int x) {this.x = x;}}}
上面這份代碼在main函數裡面會發生編譯錯誤,為瞭解決問題,讓我們先看看編譯器的提示:
編譯器告訴我們,沒有可訪問的Test類的執行個體,意味著下面將要使用執行個體,那個地方使用了呢?看後面的括弧裡面,"x.new A()",new A()實際上是x.new A(),其中x是Test的一個執行個體。所以我們可以先建立Test的一個執行個體,然後用這個執行個體的new方法new一個A()出來。
於是可以改成下面的代碼:
public class Test {public static void main(String[] args) {Test test = new Test();A a = test.new A(1);}class A {int x;public A() {}public A(int x) {this.x = x;}}}
明白了這一點就可以解釋下面的代碼了:
public class Test {public static void main(String[] args) {Test test = new Test();A a = test.new A(1);B b = new B(2);//這裡的B不是一個內部類,所以不存在上述問題所以可以直接寫newA.AA aa = a.new AA(3);}class A {int x;public A() {}public A(int x) {this.x = x;}class AA {int x;AA() {}AA(int x) {this.x = x;}}}}class B {int x;public B() {}public B(int x) {this.x = x;}}
或者用令外一種方法,將內部類改成靜態:
public class Test {public static void main(String[] args) {A a = new A();}static class A {int x;public A() {}public A(int x) {this.x = x;}}}
java中"no enclosing instance of type * is accessible"的解決方案