Below code will give error No enclosing instance of type test is accessible. Must qualify the allocation with an enclosing instance of type test (e.g. x.new A() where x is an instance of test).
class Hello { class Thing { public int size; Thing() { size = 0; } } public static void main(String[] args) { Thing thing1 = new Thing(); // This will give above error System.out.println("Hello, World!"); } }
Thing
is 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. So in code, creating an instance of Thing from a static context is throwing error.