Class Relationships

General about Class Relationships

Classes have different relations among each other. Basically we need to look at 4 parameters to determine which relation we are dealing with.

Part/Whole
Is one class a part of the other? So is it essential for one class that the other one exist?

Destructive/non-destructive behavior
If you destroy one class, is the other class also destroyed?

Inheritance
Is one class derived from another class?

Interaction
In which way are the classes interacting with each other?

Association, Dependency, Composition, Aggregation, Inheritance

Association

One Class has a reference to another class, they both are equal in their rank. In this example Student has 1..* references to Coffee.

association

Dependency

Is very similar to Association but in this case we just use a part of the API (set of available methods)  instead of the whole class.

dependency

Composition

The composition is the most used relationship, in case of a composition, one class is part of the other class and will be destroyed if the “parent” is destroyed.

Composition

Aggregation

One class is part of another class but will not be destroyed if the parent is destroyed.

Aggregation

Inheritance

One class is derived from another class, meaning that the properties (members) and methods are also available for the derived class.

Inheritance

 

From that we can set up the following table:

table

 

 

The problem with our point of view

The problem is that we as humans tend to bring classes into relations we would expect in a natural environment but this is only limited suitable for a technical implementation.

In a technical implementation we need to decide where and how the relationships are established. We can establish relationships by making classes members, point to other classes, invoke them etc. So its not sufficient to have a look at the class name but also at its attributes and methods.

Members and Pointers

So if we have a member which is another class then we have a composition because if the “parent” is destroyed, all members will also be destroyed. But how about pointers? If we point to another object and destroy the parent then just the address is lost. This would be a Aggregation in this case, but if we implement within the destructor that we also want to delete the object we are pointing to then this would be a composition. So a pointer to another class does not necessarily mean that that this is an Aggregation, it also might be an Composition but this is dependant on your implementation.

Leave a Comment

This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies.