Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k points)

I have the following code:

class Hello {

    class Thing {

        public int size;

        Thing() {

            size = 0;

        }

    }

    public static void main(String[] args) {

        Thing thing1 = new Thing();

        System.out.println("Hello, World!");

    }

}

I know Thing does nothing, but my Hello, World program compiles just fine without it. It's only my defined classes that are failing on me.

And it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing. I'm guessing either:

I have system level problems (either in DrJava or my Java install) or

I have some basic misunderstanding of how to construct a working program in java.

Any ideas?

1 Answer

0 votes
by (46k points)
static class Thing will secure your program work.

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

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

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer

Browse Categories

...