0

If I have a class such as:

public class Main {
    public class CommandLineParser {

        public CommandLineParser(String[] args) {
        }
    }

    public static void main(String[] args) {
        Main main = new Main();
        new CommandLineParser(args); // <<< line in question    
    }
}

then I, quite reasonably, get an error message:

No enclosing instance of type Main is accessible. Must qualify the allocation with an enclosing instance of type Main (e.g. x.new A() where x is an instance of Main).

But if I move class CommandLineParser to a separate file there are no such complaints.

Why is there no error in the second case?

(NOTE: This question is NOT how to instantiate non static inner class within a static method.)

Ian
  • 1,507
  • 3
  • 21
  • 36
  • Sample IS complete. Copied and pasted direct from the editor. – Ian Mar 01 '18 at 18:08
  • 1
    Maybe you wanted to create a static nested class instead of an inner class? – Mark Rotteveel Mar 01 '18 at 18:09
  • @Zabuza: Irrelevant, removed. – Ian Mar 01 '18 at 18:10
  • @Keiwan: Isn't that the opposite question? I EXPECTED to have to code x.new because of that, but if the class is external I do NOT have to. What have I missed? – Ian Mar 01 '18 at 18:13
  • It's no longer a nested class once it's in its own source file. It's a regular top level class. – Kayaman Mar 01 '18 at 18:17
  • @Kayaman: OK, but it's still NOT static. Why doesn't it require an instance there? – Ian Mar 01 '18 at 18:21
  • 2
    An instance of what? A non-static **nested** class requires an instance of the **enclosing** class. If you don't **have** an enclosing class (if you move the class to its own file it'll be a regular top level class), what instance would you even IMAGINE requiring? The duplicates explain perfectly how nested classes work. – Kayaman Mar 01 '18 at 18:22
  • @Kayaman: Ah! Your emboldening clarifies it. Many thanks. – Ian Mar 01 '18 at 18:28
  • 1
    Well it's a good thing it didn't go to *waste* :) – Kayaman Mar 01 '18 at 18:29

0 Answers0