davidk01 davidk01 - 1 year ago 134
Java Question

Java scoping rules and inner classes

All the crazy Java scoping rules are making my head spin and the public static void nonsense isn't helping matters. So far all the programming languages I have used either lexical scoping or some approximation of it without any access modifiers, i.e. inner stuff captures outer stuff and has access to the outer stuff as long as the inner stuff exists.

So how do I make sense of the scoping rules for inner classes in Java? Do they get access to variables declared in the outer class or is there some weird edge cases I have to worry about because of all the public static private stuff floating around?

Answer Source

Static inner classes are exactly like external classes except that they have access to all members of the outer class, regardless of access qualifier. They exist apart from any instance of the outer class, so need a reference to an instance in order to access any instance variables or non-static methods of the outer class.

Non-static inner classes come into existence only in the context of an instance of the outer class. When constructed, they have a second this field automatically generated, which you can access using the syntax Outer.this. Each instance of the inner class is bound to a single instance of the outer class. Again, all the access privileges of static inner classes apply to non-static inner classes. But since they already have an instance of the outer class available, they can automatically access instance variables and methods of the outer class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download