zatvornik
zatvornik

Reputation: 183

How to create instance of static nested class which contains invoked constructor (in Java)

I have given piece of code:

public class Outer {
    public static void main(String[] args) {
        //  type here
    }
    public static class Inner {
        Inner Inner = new Inner();
        public Inner() {
            System.out.println("Test");
        }
    }
}

Is it possible to create instance of class Inner by editing main method only? If yes, how to do it?

UPD: I'm sorry, I forgot to say that all the code except main method is read-only. I mean, the solution has to be written only within boundaries of main method.

Thank you

Upvotes: 0

Views: 59

Answers (2)

Aninda Bhattacharyya
Aninda Bhattacharyya

Reputation: 1251

Try this, the way to access nested static class...

public class OuterClass {
   public static void main(String[] args)
   {
        OuterClass.Inner innerObj = new OuterClass.Inner();
   }
   public static class Inner
   {
       public Inner() {
       System.out.println("Test");
   }
  }
}

Upvotes: 0

TimoStaudinger
TimoStaudinger

Reputation: 42460

You can create an instance of the inner class like any other object:

public class Outer {
    public static void main(String[] args) {
        Inner inner = new Inner();
    }

    public static class Inner {
        public Inner() {
            System.out.println("Test");
        }
    }
}

Upvotes: 1

Related Questions