How to instantiate non static inner class within a static method?

Victor Mukherjee picture Victor Mukherjee · Oct 2, 2012 · Viewed 74.7k times · Source

I have the following piece of code:

public class MyClass {

   class Inner {
     int s, e, p;
   }

   public static void main(String args[]) {
     Inner in;
   }
}

Up to this part the code is fine, but I am not able to instantiate 'in' within the main method like in = new Inner() as it is showing non static field cannot be referenced in static context.

What is the way I can do it? I do not want to make my Inner class static.

Answer

RNJ picture RNJ · Oct 2, 2012

You have to have a reference to the other outer class as well.

Inner inner = new MyClass().new Inner();

If Inner was static then it would be

Inner inner = new MyClass.Inner();