当前位置:Gxlcms > 数据库问题 > No enclosing instance of type Hello is accessible

No enclosing instance of type Hello is accessible

时间:2021-07-01 10:21:17 帮助过:2人阅读

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

标签:

人气教程排行