Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Self-Referring classes

Status
Not open for further replies.

DaDeliMan

Programmer
Feb 10, 2002
4
US
I have a Java quesion that is probrably pretty basic.
I am looking to create a class which has a child class. I want that child class to have a reference to it's parent class and vice-versa.
When initializing it, how to I create that connected reference in Java without pointers?

Would the constructor look like

Class1 class1 = new Class1();
class1.setClass2(new Class2(this));

In other words, how do I have a class pass a reference of itself to another class?


Thanks,
Bob
 
Hi Bob,

Could I just clarify something. Do you want a parent to be able to have many children, or are you looking for a one-to-one relationship?

scrat
 
Oh, I'm sorry. Yes, I would like the parent to have a reference to many children, and each of of the childen to have a reference to the parent.
 
Hi Bob,

I would do something like this...

public class Parent {

Collection children = new ArrayList();

public void addChild(Child child) {
children.add(child);
}

public void doSomethingWithChildren() {
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Child child = (Child) iterator.next();
// Do something with the child...
}
}
}

public class Child {

private Parent parent;

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

When a Child is created, it has a reference to a Parent, which it keeps in the parent member variable. It also calls the addChild method in the parent, passing itself to the parent so that the parent can add a reference of the child to its list of children. I have also included a snipet as an example of the parent doing something with the children. Hope this makes sense. If anything is unclear, let me know.

Regards,
scrat

 
P.S.

Forgot the import statements in Parent...

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

public class Parent {

Collection children = new ArrayList();

public void addChild(Child child) {
children.add(child);
}

public void doSomethingWithChildren() {
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Child child = (Child) iterator.next();
// Do something with the child...
}
}
}
 
Cool, thanks.

Would the following code snipped be cool...

Parent p = new Parent();
p.addChild(this);


Thanks a ton,
Bob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top