Kapil
Kapil

Reputation: 9969

One parent object for multiple child objects

Is it possible to have one parent object for more than one child object so that all the child could share the same parent state?

Upvotes: 0

Views: 1186

Answers (4)

Arte Arefjev
Arte Arefjev

Reputation: 41

IMO: For PHP it's possible only as simulation. Language itself does not allow it.

Upvotes: 0

djna
djna

Reputation: 55937

If your Child class derives from Parent then a Child isA Parent. If you create two Children then they are separate objects and their Parent "parts" are separate. That isn't the effect you are asking for.

I assume that scenario you want is that there can be several families. There's a Parent (call him Fred, age 72) and a Parent ( call her June, age 45)

Fred has children F1, F2, F3, June has children J1, J2.

All of Fred's children have age 72, June's 45, and when we pass Fred's birthday all his children automatically age to 73.

So we model this by a hasA relationship.

Child { 
     Parent myParent;  // points to Fred or June, or whoever
     int getAge() { return myParent.getAge(); }
}

Note that we end up delegating to our parent, which is slightly more work than using inheritance, but is probably what you want to do.

Upvotes: 1

Björn Pollex
Björn Pollex

Reputation: 76848

The Flyweight-Pattern might help you. Or not. For a more specific answer, please make your question more precise, best would be a description of you actual use case.

Upvotes: 0

Ben
Ben

Reputation: 11208

Yes that is possible. I have an ArrayList class for that, an ArrayList is actually a normal array but I only allow objects to be in it.

Take a look at the ArrayList class from Microsoft, mine is based on that one.

Upvotes: 0

Related Questions