. Advertisement .
..3..
. Advertisement .
..4..
I’m trying to run a new project. I do a couple of things like this:
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!");
}
}
But in my program, I am getting the warning:
No enclosing instance of type Hello is accessible
Can someone explain why the “no enclosing instance of type is accessible” issue happened? Where have I gone wrong? Thank you!
The cause:
From your program I found that the class of
Thing
was declared as a non-static inner class. This implies that it must be connected to aHello
class instance. You are attempting to build aThing
instance from a static context in your code. However, static methods did not have permission to access to a non-static inner class. This is the reason for your mistake.Solution:
static class Thing
can solve your problem and help your program run well. A specificHello
instance must be in scope fornew Thing()
to work if you have specifiedThing
as an inner class, which is linked to a specific instance ofHello
by definition (even if you never use or refer to it). If you declare it as a static type rather than a dynamic class, it will become “nested”, and you do not need aHello
instance.The class
Thing
has been declared as an inner non-static class. This means that it must be associated to an instance ofHello
class.You are trying to create a
Thing
instance from a static context. This is what the compiler is complaining.There are many possible solutions. Depending on your goals, there are a few options.
Move
Thing
from theHello
classification.Thing
should be changed tostatic
nested classes.Before creating an instance
Hello
, create .If
Thing
relied onHello
for meaning, the last solution (a nonstatic nest class) would be mandatory. If we had:Any attempt to create an object from class
Thing
raw, such as:It would be difficult to test 31 against it, as there isn’t an obvious
enormous
value. To provide thish.enormous
value, an instanceh
from theHello
outer classes is required:It doesn’t necessarily mean a
Thing
if it does not have aHello
.For more information about inner/nested classes, see Nested Class (The Java Tutorials).