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

JavaInner Classes

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

      static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

      public static void main(String[] args)
      {
          Hello h = new Hello();
          Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
      }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

Solution 3 - Java

Well... so many good answers but i wanna to add more on it. A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages:

  1. It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.

  2. It can make code more maintainable as the classes are logically grouped together around where they are needed.

  3. The inner class has access to the instance variables and methods of its containing class.

We have mainly three types of Inner Classes

  1. Local inner
  2. Static Inner Class
  3. Anonymous Inner Class

Some of the important points to be remember

  • We need class object to access the Local Inner Class in which it exist.
  • Static Inner Class get directly accessed same as like any other static method of the same class in which it is exists.
  • Anonymous Inner Class are not visible to out side world as well as to the other methods or classes of the same class(in which it is exist) and it is used on the point where it is declared.

Let`s try to see the above concepts practically_

public class MyInnerClass {

public static void main(String args[]) throws InterruptedException {
	// direct access to inner class method
	new MyInnerClass.StaticInnerClass().staticInnerClassMethod();

	// static inner class reference object
	StaticInnerClass staticInnerclass = new StaticInnerClass();
	staticInnerclass.staticInnerClassMethod();

	// access local inner class
	LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
	localInnerClass.localInnerClassMethod();

	/*
	 * Pay attention to the opening curly braces and the fact that there's a
	 * semicolon at the very end, once the anonymous class is created:
	 */
    /*
	 AnonymousClass anonymousClass = new AnonymousClass() {
		 // your code goes here...
		 
	 };*/
 }

// static inner class
static class StaticInnerClass {
	public void staticInnerClassMethod() {
		System.out.println("Hay... from Static Inner class!");
	}
}

// local inner class
class LocalInnerClass {
	public void localInnerClassMethod() {
		System.out.println("Hay... from local Inner class!");
	}
 }

}

I hope this will helps to everyone. Please refer for more

Solution 4 - Java

Thing is an inner class with an automatic connection to an instance of Hello. You get a compile error because there is no instance of Hello for it to attach to. You can fix it most easily by changing it to a static nested class which has no connection:

static class Thing

Solution 5 - Java

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

	public static void main(String[] args) {

		// create dog object here
		Dog dog = new PQ().new Dog();
		//OR
		PQ pq = new PQ();
		Dog dog1 = pq.new Dog();
	}

	abstract class Animal {
		abstract void checkup();
	}

	class Dog extends Animal {
		@Override
		void checkup() {
			System.out.println("Dog checkup");

		}
	}

	class Cat extends Animal {
		@Override
		void checkup() {
			System.out.println("Cat Checkup");

		}
	}
}

Solution 6 - Java

Before Java 14 You have to add static keyword to access class Thing from the static context.

class Hello {
    static class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
        Thing thing1 = new Thing();
        System.out.println("Hello, World!");
    }
}

Java 14+ Starting from Java 14 you can use inner record classes they are implicitly static. So you would have:

class Hello {
    record Thing(int size) { }

    public static void main(String[] args) {
        Thing thing1 = new Thing(0);
        System.out.println("Hello, World!");
    }
}

Solution 7 - Java

Declare the INNER class Thing as a static and it will work with no issues.

I remember I have the same issue with the inner class Dog when I declared it as class Dog { only. I got the same issue as you did. There were two solutions:

1- To declare the inner class Dog as static. Or

2- To move the inner class Dog to a new class by itself.

Here is the Example:

public class ReturnDemo {

public static void main(String[] args) {
	
	int z = ReturnDemo.calculate(10, 12);
	System.out.println("z = " + z);
	
	ReturnDemo.Dog dog = new Dog("Bosh", " Doggy");
	System.out.println( dog.getDog());
}


public static int calculate (int x, int y) {
	return x + y;
}

public void print( ) {
	System.out.println("void method");
	return;
}

public String getString() {
	return "Retrun String type value";
}


static class Dog {
	
private String breed;
private String name;

public Dog(String breed, String name) {
	super();
	this.breed = breed;
	this.name = name;
}

public Dog getDog() {
	// return Dog type;
	return this;
	
}

public String toString() {
	return "breed" + breed.concat("name: " + name);
}
}

}

Solution 8 - Java

Try this my friend: (you can also call it Hello instead of Main)

class Thing {
  public int size;

    Thing() {
      size = 0;
    }
}


class Main {
  public static void main(String[] args) {
    Thing thing1 = new Thing();
      System.out.println("Hello, World!");
  }
}

The idea behind this is that you have to create a separate class to include the static void main (String[] args) method. Summing up: you must have a class that will create your objects, and another class (outside the previous one) in which you'll include the object creation. If you call it Main, you should have a file called Main.java. If you want to call it Hello, then your file must be named Hello.java

Solution 9 - Java

class Hello {
    class Thing {
        public int size;

        Thing() {
            size = 0;
        }
    }

    public static void main(String[] args) {
    	
    	PlayGround obj = new PlayGround();
        
    	Thing obj2 = obj.new Thing();
    	
    	System.out.println("Hello, World!");
    }
}

Solution 10 - Java

In my case it was because of one extra '}'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoolpapaView Question on Stackoverflow
Solution 1 - JavajacobmView Answer on Stackoverflow
Solution 2 - Javahelloworld922View Answer on Stackoverflow
Solution 3 - JavaRupesh YadavView Answer on Stackoverflow
Solution 4 - JavaDavid HarknessView Answer on Stackoverflow
Solution 5 - JavaAZ_View Answer on Stackoverflow
Solution 6 - JavaŁukasz RzeszotarskiView Answer on Stackoverflow
Solution 7 - JavaMaged AlmaweriView Answer on Stackoverflow
Solution 8 - JavaJohannView Answer on Stackoverflow
Solution 9 - JavaMarkView Answer on Stackoverflow
Solution 10 - JavaRabhi salimView Answer on Stackoverflow