wood burning stoves 2.0*
The moose likes Java in General and the fly likes When do we use nested classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "When do we use nested classes" Watch "When do we use nested classes" New topic
Author

When do we use nested classes

Nittin singla
Greenhorn

Joined: Jul 02, 2011
Posts: 24
Hi All,

I am clear about the functionality of nested classes. But what i want to ask is when to use the nested classes.

TIA
AbdulRab Khan
Greenhorn

Joined: Nov 11, 2011
Posts: 7

One of the example could be a scenario where you wanted to use one class into another, and this class is no longer to be used by any other classes. So there is no need to put this class as a Top level class.

For Example

Class A {


Class B {}//You know that there is no use of Class 'B' outside class 'A'

}
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7713
    
  20

Nittin singla wrote:I am clear about the functionality of nested classes. But what i want to ask is when to use the nested classes.

Truly nested classes (ie, a non-static inner class) are rare, but can be used to make an Adapter. An example of this might be a particular type of Iterator for a class, because it needs access to an actual instance of the collection. Static nested classes are much more common, and are just like any other class, except that they're associated with the 'outer' class. An example of that is AbstractMap.SimpleEntry: the class really only has meaning when associated with an AbstractMap, so it makes sense to define it inside.

HIH

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Winston Gutkowski wrote:
Nittin singla wrote:I am clear about the functionality of nested classes. But what i want to ask is when to use the nested classes.

Truly nested classes (ie, a non-static inner class) are rare


I'm pretty sure you've got the terminology backwards. A nested class is any class declared inside another class, and an inner class is a non-static nested class.

</nitpick>
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7713
    
  20

Jeff Verdegan wrote:I'm pretty sure you've got the terminology backwards. A nested class is any class declared inside another class, and an inner class is a non-static nested class.

You're quite right, 'truly nested' probably wasn't the best description, but it's the way I think of them. I was just trying to make the distinction for OP.

Winston
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
Is accessing the instance members of the enclosing class the only criteria for choosing between non-static vs static classes? It still is kind of a bit confusing. Can someone provide an example of nested non-static class and explain why static nested class would not be correct, and vice-versa.

Thanks in advance.
Amit
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Amit J Thakur wrote:Is accessing the instance members of the enclosing class the only criteria for choosing between non-static vs static classes?


That's pretty much it in my book. If the nested class is tied to a single instance of the enclosing class, it MUST be non-static else stuff won't work. Static classes, on the other hand, often could work as non-static, and in that case the reason I would make them static is to affirm that they're not tied to an instance.
Mike Okri
Ranch Hand

Joined: Jun 22, 2011
Posts: 83
Amit J Thakur wrote:Is accessing the instance members of the enclosing class the only criteria for choosing between non-static vs static classes?

A nested class must be static if it has static members or if it accesses static members of its outer class; otherwise, it must be a non-static.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4375
    
    8

Mike Okri wrote:A nested class must be static if it has static members or if it accesses static members of its outer class; otherwise, it must be a non-static.

That's not right. A non-static nested class can access static members of the outer class (just as non-static methods of the outer class can). But you need a non-static inner class if you want to access non-static members of the outer class (unless they're accessed through an outer-class object reference).
Mike Okri
Ranch Hand

Joined: Jun 22, 2011
Posts: 83
Sorry. My mistake.

If a nested class has static members, it must be static.
If a nested class accesses non-static members of its outer class, it must be non-static.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

I don't really think there's much use for static members in an inner class anyway. I usually use this simple rule for myself:

Use a non-static class only if the class needs to access non-static members of its enclosing class.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7713
    
  20

Amit J Thakur wrote:Can someone provide an example of nested non-static class and explain why static nested class would not be correct, and vice-versa.

I believe I did in my first post, but there's another one in the tutorials here which may explain it better.

Winston
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
Thanks everyone for your replies.

Are there any well known libraries/classes which uses Nested (both static and non-static classes). I can take a look at it to understand the concepts better.

That's pretty much it in my book.

Jeff, could you give me the name of the book you are referring to.

Thanks,
Amit
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
Thanks Winston.
I somehow missed the examples in your post. I will take a look at them.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3615
    
  14

Amit J Thakur wrote:Jeff, could you give me the name of the book you are referring to.

Haha, don't worry about it. Jeff used a common English expression which basically means he strongly believes something. In this case he strongly believes accessing instance members of the enclosing class is the only criterion. There's no actual book.
Mike Okri
Ranch Hand

Joined: Jun 22, 2011
Posts: 83
Amit J Thakur wrote:Are there any well known libraries/classes which uses Nested (both static and non-static classes). I can take a look at it to understand the concepts better.


The JButton class has a package-private, non-static nested class called Handler.


The Rectangle2D class has a public, static nested class called Double.


Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4340
    
    2

when i wrote my first non-trivial applet back in 2000, it had two inner classes. it was a terrible design. partly because i didn't understand OOP, and partly because i kept adding new features. the only thing it had going for it is that it worked. when i recently started writing java again, the first thing i tackled was to refactor it.


SCJP
Visit my download page
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
Thanks everyone.

Stephan van Hulst wrote:Haha, don't worry about it. Jeff used a common English expression which basically means he strongly believes something.

Was working late in the night and was probably sleepy, so when I read Jeff's comment I thought he had authored some book which he is referring to . But to be honest, I was not aware of this expression either. I too found it funny and laughed when I saw your clarification

Mike I will take a look at the classes that you pointed to.

The discussion brings out one more question to my mind i.e. related to the lifecycle of the objects created by static & non-static nested classes.

For example:



Following is my understanding based on the above experiment that I did. Can someone ratify the same.

The object of non-static nested class has an implicit reference to the enclosing class object, hence it does not get garbage collected even when the client class makes the list=null.

As in the case of static nested class, the reference to the enclosing class object is not required. This brings me to another question on the implementation of Map as pointed by Winston.
The Map has a static nested type i.e. Entry. Some developer can create a map, assign the reference of the Map.Entry objects to some variable and then assign null to the map object (As per my understand this map object will be marked for gc.). But as the existence of static nested objects doesnt require enclosing class object, these object(Map.Entry) will be there in the memory as they are still being referenced by some variable. If this is true, is this a good design as the existence of Map.Entry doesn't make sense without the enclosing Map object.

Am just trying to create a model mentally to understand this better. Is there any article/blog/book that would clear my understanding about the internals.

Thanks,
Amit
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7713
    
  20

Amit J Thakur wrote:The object of non-static nested class has an implicit reference to the enclosing class object, hence it does not get garbage collected even when the client class makes the list=null.

Basically, you're correct, except that it's probably easier to say that an inner class is not eligible for garbage collection until it's enclosing instance is. However, the same is also true of the enclosing instance - IT is not available for garbage collection as long as any external reference to the inner class exists.

...Some developer can create a map, assign the reference of the Map.Entry objects to some variable and then assign null to the map object (As per my understand this map object will be marked for gc.). But as the existence of static nested objects doesnt require enclosing class object, these object(Map.Entry) will be there in the memory as they are still being referenced by some variable. If this is true, is this a good design as the existence of Map.Entry doesn't make sense without the enclosing Map object.

I think maybe you're misinterpreting what I said: the definition of a Map.Entry doesn't make any sense without Map, because one is only used with the other (although in that particular case both are interfaces, not classes). To me it makes perfect sense that you wouldn't want to keep an entire Map around just because some idiot holds on to a single Entry like a limpet.

HIH

Winston
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
Surely it helps Winston. Thanks for taking out time.

Winston Gutkowski wrote: Basically, you're correct, except that it's probably easier to say that an inner class is not eligible for garbage collection until it's enclosing instance is.

Am I missing something here? As per my understanding, an inner class will be eligible for garbage collection unless it referenced explicitly by either an enclosing class or some other outside class.
In the above code, if node2 is made null, are you saying that the enclosing class has an implicit reference to this inner class?


To me it makes perfect sense that you wouldn't want to keep an entire Map around just because some idiot holds on to a single Entry like a limpet.

My point was that someone may inadvertently hold a reference to Entry objects and whether the possibility exists [in nested static classes]. The conclusion is that it is possible to do this but one needs to avoid such situation, advertently or inadvertently. But as a design, can we enforce, so that such mistakes can be avoided by the user of such classes.

Thanks,
Amit
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 7713
    
  20

Amit J Thakur wrote:Am I missing something here? As per my understanding, an inner class will be eligible for garbage collection unless it referenced explicitly by either an enclosing class or some other outside class.

My apologies; I was completely wrong (Not the first time, won't be the last. I had to go back and re-read the chapter on inner (non-static) classes because I use them so rarely). And the answer to your question is: no, the outer class does not contain any implicit reference to an inner class, so the inner class can be made eligible for removal independent of its outer class (but not vice-versa).

Just FYI, another concrete example of an inner class are the "views" returned by java.util.Map implementations. Have a look at keySet(), entrySet() and values() methods.

My point was that someone may inadvertently hold a reference to Entry objects and whether the possibility exists [in nested static classes]. The conclusion is that it is possible to do this but one needs to avoid such situation, advertently or inadvertently. But as a design, can we enforce, so that such mistakes can be avoided by the user of such classes.

Possibly, but it may be more trouble than it's worth. At least with a static nested class you reduce the effect of bad handling, because the outer class is not connected to it.

I've always found it easiest to think of a static nested class as just a regular class that happens to be defined inside another one for semantic reasons.

Winston
Amit J Thakur
Greenhorn

Joined: Sep 26, 2011
Posts: 13
My apologies; I was completely wrong (Not the first time, won't be the last. I had to go back and re-read the chapter on inner (non-static) classes because I use them so rarely).

Everyone makes mistakes, and it is a healthy discussion from which I have learnt and benefited. Don't worry too much about it . And yes, I really appreciate you taking out time to re-read the chapter.


Just FYI, another concrete example of an inner class are the "views" returned by java.util.Map implementations. Have a look at keySet(), entrySet() and values() methods.

Thanks for the reference. I had had a cursory look at the implementation of HashMap, though I would take out sometime to go through it later.

I've always found it easiest to think of a static nested class as just a regular class that happens to be defined inside another one for semantic reasons.

I too agree on this.

I will dive further into this topic of nested types, and would be back if I have any further doubts . Thanks once again!

Amit
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: When do we use nested classes