Woozle Wuzzle
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?

Comments
Comment by Brandon Franklin at April 27, 2005 06:58 PM

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.

 

Comment by rgrzywinski at April 27, 2005 08:01 PM

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*)

 

Comment by Brandon Franklin at April 27, 2005 11:24 PM

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. :)

 

Comment by rgrzywinski at April 28, 2005 06:32 AM

I agree with you. I'm going to feign ignorance from now on, but I'll always have that lingering feeling that I'm not as safe as I once thought I was.

 

Comment by vinod at March 13, 2006 08:24 AM

how can I get familiar with inner/nested classes

 

Comment by rgrzywinski at March 14, 2006 06:58 AM

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!

 

Post a comment













Remember personal info?






Creative Commons License Unless otherwise expressly stated, all original material of whatever nature created by Rob Grzywinski and included in this weblog and any related pages, including the weblog's archives, is licensed under a Creative Commons License.