0

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

3
  • 1
    Inner inner = new Inner(); Also, it's not quite clear to me why Inner has an instance of itself. Commented Jul 31, 2015 at 14:19
  • Will this not lead to a kind of endless recursion, when Inner has an Inner has an Inner.... ? Commented Jul 31, 2015 at 14:23
  • @UweAllner It will, if you instantiate the class Inner as shown in the example. Commented Jul 31, 2015 at 14:39

2 Answers 2

1

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");
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

It works... But according to conditions of this "exercise" I can't edit any code except main method
@Weirdo are you sure this exercise is given exactly as stated in the Question? Instantiating the inner class as it is implemented in the example code would result in a StackOverflowError, since it is recursively instantiating itself.
Doublechecked it. Yes, I'm sure. This is the reason why I decided to post this question here :)
Do you have any additional context for that question that might be relevant?
I do, but nothing important, I suppose. Complete requirement of exercise is as follows: "Create 7 objects to display 7 days of the week. During creation each object displays specific day of the week." Then goes code where Inner class is named Monday, then goes Tuesday, then Wednesday and so on, 7 same nested classes, differ only by a name. So, nothing signicant, I think.
0

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");
   }
  }
}

1 Comment

This works either. But I want to reach this result without editing nested class - if it's possible :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.