File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Nested Classes or Objects as Members Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Nested Classes or Objects as Members" Watch "Nested Classes or Objects as Members" New topic

Nested Classes or Objects as Members

Madhur Baheti

Joined: Nov 30, 2000
Posts: 12
Can someone please explain me that which should be used when:
1. Inner Nested classes
2. Including in one class the object/s of another class as its members
Please explain with examples.
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
You should only use an inner class when the definition of that class is ONLY related to the enclosing class. If you make it an inner class, then you never run the risk of some other programmer trying to use that class for something that it was not intended for.
Conceptually an inner class should define something that is an integral part of the enclosing class. For instance, you might have a class for Body, which has inner classes for Eye, Heart, Kidney etc. This implies that you would not have an instance of Heart without understanding it in relation to the particular body that it belongs to and you would never create a Heart without the body.
From Mother Natures point of view this makes all the sense in the world. Of course this makes it difficult to track Heart transplants.
If you include an instance of another class in a class, then it is a "has a" relationship. A person "has a" spouse, but the spouse exists outside of the relationship to the person. The spouse person also has some meaning in the world that is unrelated to the fact that it is a spouse (probably ). For instance the spouse could be an employee of a company, with or without being married.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Madhur Baheti

Joined: Nov 30, 2000
Posts: 12
Thanks. I got the idea.
I agree. Here's the link:
subject: Nested Classes or Objects as Members
It's not a secret anymore!