Java’s Nested Classes

Most everyone knows that a nested class can access private memebers of its enclosing class. But did you know that the reverse is true? The enclosing class can access private members of the nested class. No, really.

For those doubting Thomas’ out there, I’ll provide you with a reference.

Does anyone know the motivation behind why the enclosing class would be able to access private members of the nested class?

Advertisements

7 comments

  1. I will admit this was news to me.
    I certainly haven’t been writing (and probably won’t write) my inner classes to take advantage of that fact. I prefer the control and readability you get by using accessors.

  2. The hitch here is that you can “accidentally” access a member, -any- member, directly. This means both fields -and- methods (and further nested types).
    The way that I found this was doing a lazy developer’s trick whereby I make a method private and just walk through the errors to make the mods that I needed to mod (this wasn’t something that I could refactor automagically) and then set the method back public. Much to my surprise and dismay, setting the method to private -did nothing-.
    Java — how to suck the sap out of a developer in one easy step. (Sorry, I’m a bit bitter right now *grin*)

  3. That is kinda scary, but I’m still going to write my code as if it wasn’t true, is what I’m saying. Source code, in the end, is more about the human aspect than anything else anyway, so making it readable is paramount to me.
    BTW, I do that trick too, but I comment the stuff out instead of making it private. šŸ™‚

  4. Vinod: other than going to Google and typing “inner class tutorial” or “nested class tutorial” and going through the 1000000 tutorials that you’re going to find, you could sit down with your favorite IDE and start writing some classes and see what happens. There’s no better way to learn something than to try a few cases.
    Good luck!

  5. Yeah, it’s in fact quite sad that there is two directional visiblitiy between main and inner class. This makes inner classes in some cases useless because it’s better to create top-level package visibility class and explicitly couple it with main class either by naming convention or by passing the reference to. šŸ˜¦ Once again, it’s very disappioiting to me :(.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s