Java - No enclosing instance of type Foo is accessible

后端 未结 5 1140
再見小時候
再見小時候 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

    static class Thing will make your program work.

    As it is, you've got Thing as an inner class, which (by definition) is associated with a particular instance of Hello (even if it never uses or refers to it), which means it's an error to say new Thing(); without having a particular Hello instance in scope.

    If you declare it as a static class instead, then it's a "nested" class, which doesn't need a particular Hello instance.

提交回复
热议问题