Java - No enclosing instance of type Foo is accessible

后端 未结 5 1138
再見小時候
再見小時候 2020-11-21 06:35

I have the following code:

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public stat         


        
5条回答
  •  鱼传尺愫
    2020-11-21 06:53

    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.

    • Move Thing out of the Hello class.

    • Change Thing to be a static nested class.

      static class Thing
      
    • Create an instance of Hello before creating an instance of Thing.

      public static void main(String[] args)
      {
          Hello h = new Hello();
          Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
      }
      

    The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

    public class Hello {
        public int enormous;
    
        public Hello(int n) {
            enormous = n;
        }
    
        public class Thing {
            public int size;
    
            public Thing(int m) {
                if (m > enormous)
                    size = enormous;
                else
                    size = m;
            }
        }
        ...
    }
    

    any raw attempt to create an object of class Thing, as in:

    Thing t = new Thing(31);
    

    would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

    ...
    Hello h = new Hello(30);
    ...
    Thing t = h.new Thing(31);
    ...
    

    Because it doesn't mean a Thing if it doesn't have a Hello.

    For more information on nested/inner classes: Nested Classes (The Java Tutorials)

提交回复
热议问题