I've an abstract class Area, which is subclassed as Province, Division, District and City.

Now, I need to specify in the City class in which district this city exists. So, I will have an instance of District class inside City class (Composition), so that I could pass id of a specific district to the city and that will be stored in database city tables. But, it doesn't follow the rules of composition. As District-has-City and not the other way.

And another problem is that both classes are use inheritance and composition, which I feel is not right.

I've been trying to solve this on my own for a week by googling and other stuff. But, I'm unable to solve this issue. It's my last hope i guess. How would I solve this? any example?

PS: is this diagram correct? http://prnt.sc/abuam1

There's nothing wrong with what you are doing. It happens all the time, eg
Employee has a subclass Manager (inheritance)
Every Employee has a Manager (composition)
Every Manager manages (has) several Employees (composition)

technically only one of those composition relationships needs to be held, and holding them both does pose a possible risk of inconsistent data (beware multiple threads!), but its common to keep both for reasons of code simplicity and performance. Of course you will wrap those relationships inside accessor methods, so the implementation of how/whether they are held as data will be hidden and changeable.

ps: I used your term "composition", but more correctly this kind of relationship is called "aggregation" because it does not have the lifetime dependenecy that is implied by composition. You model it in UML with a hollow diamond at the containing end.

Edited 9 Months Ago by JamesCherrill

This article has been dead for over six months. Start a new discussion instead.