No enclosing instance of type Hello is accessible

來源:互聯網
上載者:User

標籤:

1.static 關鍵字
  • 修飾的成員被所有對象共用(包括成員變數和方法)。
  • 修飾的成員優先於對象存在。
  • 儲存於方法區(共用資料區)的靜態區中。
  • 靜態方法只能訪問靜態成員。
  • 靜態方法中不可以使用this或super關鍵字。
  • 主函數是static,只能調用static方法。
  • 靜態代碼塊隨著類的載入而運行(只執行一次)。用於給類進行初始化。

Q:

I have the following code:

   1: class Hello {
   2:     class Thing {
   3:         public int size;
   4:  
   5:         Thing() {
   6:             size = 0;
   7:         }
   8:     }
   9:  
  10:     public static void main(String[] args) {
  11:         Thing thing1 = new Thing();
  12:         System.out.println("Hello, World!");
  13:     }
  14: }

it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing.

 

A:

You‘ve declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you‘re trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Change Thing to be a static nested class.

       1: static class Thing
  • Create an instance of Hello, then create an instance of Thing.

       1: public static void main(String[] args)
       2: {
       3:     Hello h = new Hello();
       4:     Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
       5: }
  • Move Thing out of the Hello class.

No enclosing instance of type Hello 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.