Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
What's the best Object-oriented way to implement parent-child relationships in Java?
Suppose you have a parent object with numberous child objects, and each of these has numerous child objects. What's the best way to implement this so that each child knows who its parent is, and each parent knows who all its children are?
The obvious way is with pointers and arrays, but then how would a child know which is its parent, unless you have a list of all the parents and children in some other object.
3 Answers
- 2 decades agoFavorite Answer
What you want is the "Composite Design Pattern". Google it for a bunch of results. There a JavaWorld link in the sources section as well.
The composite design pattern is the object oriented data structure that models exatly what you're interested in. Most representations don't deal with looking back up at a parent, but that's pretty easy to address.
In the child's constructor, add an argument for the parent's class, which is stored as an attribute in the child. When the child is constructed, the parent passes "this" to it, and the connection is made.
Addition care may be needed to prevent the constructor from looking like a copy constructor. You could also set the parent with a set accessor after the child has been created.
If you like the composite design pattern, expore more of them. There are about 2 dozen. I just them all of the time in my software designing.
- Anonymous2 decades ago
Using the Class class, it's easy to find all the super classes of an object:
List<Class> superclasses = new ArrayList<Class>( );
Class c = new YourChildObject( ).getClass( );
while ( c.getSuperclass( ) != null )
{
c = c.getSuperclass( );
superclasses.add( c );
}
I don't know about finding all the child classes though.
- 2 decades ago
I think this is what you are looking for. Add some more info if it isn't.