java中"no enclosing instance of type * is accessible"的解決方案

來源:互聯網
上載者:User

標籤:

這種情況一般發生在“在靜態方法裡面使用內部類”

測試代碼:

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"的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.