It's not a secret anymore!
The moose likes Beginning Java and the fly likes Nested static classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Nested static classes" Watch "Nested static classes" New topic

Nested static classes

Raghuveer Kumarakrishnan
Ranch Hand

Joined: Mar 13, 2005
Posts: 32
Hi all I am a newbie to both javaranch and java. I was reading up on nested static classes.Is there a good rule of thumb when you would want to include them in your program design.Are there some obvious scenarios which call for using them.


Raghu<br />SCJP 1.4<br />SCWCD 1.4<br />SCBCD 1.3
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
One reason you may nest is that the class represents a subordinate concept:

Here Link is only useful in the presence of LinkedList.

A second reason is hiding: you can make the nested class private, an access
level that top-level classes can't enjoy (because it makes no sense for them!)
Again in this example, making Link private makes it an implementation detail
of LinkedList, hidden from other classes outside of LinkedList.

This second reason is less compelling to me, because you can give top-level
classes default level access and then they'll be inaccessible to classes
outside this package, which is usually sufficient, as far as hiding
implementation details goes.

A third reason is that nested classes can access private members of outer
classes. In C++, they have a saying: friends can touch your private parts:

This is justified because one thinks of Link as being part of LinkedList's
implementation, and one part of an implementation always has access to all
the other parts.

I find I do use this feature often, but for inner classes -- non-static --
versus static nested classes. I think that's because my few nested static
classes tend to be of the simple, Link, variety.

There is no emoticon for what I am feeling!
Raghuveer Kumarakrishnan
Ranch Hand

Joined: Mar 13, 2005
Posts: 32
Thanks Jeff I think I got it now.
I agree. Here's the link:
subject: Nested static classes
It's not a secret anymore!