• Register
1 vote
142 views

Problem:

Hi

I was just learning and practicing java inner class and instance. Here I created a demo inner class though it does nothing in my program I know that. Without the inner class my code compiles well and prints Hello World. When I add the inner class it throws back the error again.
Any solution?

class Hello {
    class Demo {
        public int size;

        Demo() {
            size = 0;
        }
    }

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

 

15.3k points

Please log in or register to answer this question.

1 Answer

0 votes

Solution:

The no enclosing instance of type is accessible is a compilation based error. It occurs when you are trying to initialize the instance of an inner class without specifying the instance of the outer class. Inner classes are not accessible directly using the Outer class name as only static inner classes are accessible that way.
 

Check below programs

public class OuterClass {

     public class InnerClass {
     }
} 

OuterClass.InnerClass = new OuterClass.InnerClass(); // This line gives error

To avoid this error either make the inner class as a static inner class or Initialize the Inner class using the Outer class instance.

As a static class (Inner class):

public class OuterClass {

     public static class InnerClass {
     }
} 

OuterClass.InnerClass = new OuterClass.InnerClass(); 


Initializing the inner class:

public class OuterClass {

     public class InnerClass {
     }
} 

OuterClass.InnerClass = new OuterClass.new InnerClass(); 

This should work fine now.

94.3k points