Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?

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:

  1. I have system level problems (either in DrJava or my Java install) or
  2. I have some basic misunderstanding of how to construct a working program in java.

Any ideas?

like image 955
coolpapa Avatar asked Mar 05 '12 01:03

coolpapa


People also ask

How do I fix No enclosing instance of type is accessible?

Solution 1 If the non static inner class is modified to the static inner class, the static method will provide access to the static inner class. Changing the non static to the static inner class would fix the exception.

Is not an enclosing class Java error?

In this situation the "not an enclosing class" error is due to incorrect use of this . this , within an instance method or constructor, refers to the current object. Using MainActivity. this is referring to the object MainActivity as if it were the current object but the current object is of type TestHandler .

What is inner class in Java with example?

Java inner class or nested class is a class that is declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.


1 Answers

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.

like image 54
jacobm Avatar answered Sep 21 '22 20:09

jacobm