-1

Why inside Main.class to instantiate a Foo class(its inner class) I have to specify it with static keyword but if I make this class as outer it is possible without 'static'?

public class Main {

    public static void main(String[] args) {
        Foo foo = new Foo();
    }

//    class Foo { // to make it work I have to add 'static'
//    }
}

But if Foo.class is not Inner class of Main.class it works.

public class Main {

    public static void main(String[] args) {
        Foo foo = new Foo();
    }

}

class Foo {
}
0seNse0
  • 43
  • 5
  • ['Static inner' is a contradiction in terms](https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.1.3): 'an inner class is a nested class that is not explicitly or implicitly declared `static`. – user207421 Jun 19 '19 at 11:19
  • Though the question is different from this one, it’s related, and I think you may also find *your* answer there: [Java inner class and static nested class](https://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class). – Ole V.V. Jun 19 '19 at 11:26
  • 1
    @Ole V.V. I believe the question you linked to does indeed answer this question. – rghome Jun 19 '19 at 11:28

1 Answers1

0

If you declare the class as a non-static inner class it belongs to an instance of the outer class. In your static main method you don't have an instance (because the method is static) so you're not allowed to access the class.

If you declare it as an outer class the Foo class is just a normal class that can be accessed from static and non-static methods because it does no longer belong to an instance of the outer class.

Tobias
  • 2,547
  • 3
  • 14
  • 29