0

Possible Duplicate:
Java: Static vs non static inner class

What is a static nested class? What is the difference between static and non-static nested classes?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

11

A static inner class is a class nested inside another class that has the static modifier. It's pretty much identical to a top-level class, except it has access to the private members of the class it's defined inside of.

class Outer {
    private static int x;
    static class Inner1 {
    }
    class Inner2 {
    }
}

Class Inner1 is a static inner class. Class Inner2 is an inner class that's not static. The difference between the two is that instances of the non-static inner class are permanently attached to an instance of Outer -- you can't create an Inner2 without an Outer. You can create Inner1 object independently, though.

Code in Outer, Inner1 and Inner2 can all access x; no other code will be allowed to.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • I think you are wrong regarding: "except it has access to the private members of the class it's defined inside of" You will get compile time error "Cannot make a static reference to the non-static field", Static class wont have access to any nonstatic member of outer/enclosing class – baboo May 06 '15 at 10:40
  • 1
    You are confusing the concept of access control with actually having members to access. Code in the static inner class is allowed to see all members of enclosing class in exactly the same way as code in a static method of the enclosing class would; if the static code has an instance of the enclosing class to work with, it can see all the members of that instance. – Ernest Friedman-Hill May 06 '15 at 10:52
  • okay, got what you mean , :) , my bad – baboo May 06 '15 at 11:20
  • Perhaps show Outer2, a class which is outside of the Outer class, and compare that with Inner1/Inner2. Please. –  Nov 17 '18 at 00:10
  • 1
    @MrCholo Added a bit. – Ernest Friedman-Hill Nov 17 '18 at 01:06
  • @ErnestFriedman-Hill I meant this https://gist.github.com/the1mills/fa0e6a49008368d4ab279e8c0fc65767 but it might be outside the scope of the OP. Feel free to comment on the gist thread tho, thx. –  Nov 17 '18 at 02:07