Search code examples
javaobjectreferencestructureparent

Structuring parent and sub classes references


I'd like to create multiple parents, each parent contains multiple children. The problem is that i want only one parent for each set of children, and each of the children must know about their parent and vice versa. Set of children share one instance of the parent - it's methods and variables. So if one of the children change parent variable, all of the rest children would get the same result.

Idea

http://oi57.tinypic.com/6ohh7n.jpg

What i tried

  • using inheritance, but that resulted in creating separate parent object for each child, which is what i don't want.
  • parent reference injection in child constructor, like this
//reference injection
class Parent{
    public Parent(){
        children = new Child[10];

        for(int i = 0; i < children.length; i++){
            children[i] = new Child(this);
        }
    }

    Child[] children;
}

class Child{
    public Child(Parent parent){
        this.parent = parent;                        
    }

    private Parent parent;
    public Parent getParent(){return parent;}
}

Parent parent = new Parent();
Child child1 = new Child(parent);
Child child2 = new Child(parent);
Child child3 = new Child(parent);

But this doesn't feel solid, because i have to pass this in constructor and it doesn't feels like a good approach.

What might be the best approach doing this?

Thank you very much.


Solution

  • "Best" questions are usually off-topic for Stack Overflow, but for what it's worth, the approach you've shown code for is perfectly normal, the standard way to do this. For the children to know who their parent is, you have to tell them who their parent is. So passing them a reference to their parent at some stage is the way you'd most likely do that. If you're creating the children within a parent instance method, passing in this is perfectly appropriate.


    Separately:

    So if one of the children change parent variable...

    If the number of children in the parent may vary, an array probably isn't the best way to store them. One of the List implementations (ArrayList, LinkedList, etc.) would be more typical.