No enclosing instance of type Hello is accessible

时间:2021-11-20 03:24:48

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.