You can use an association to connect two Classes in your model, including connecting a Class to itself, when information is a relationship rather than a single attribute value.
Contents
Create an association
An association describes how Classes relate to each other. Use an association when an object needs to refer to objects of another Class, or when it needs to handle a list of related objects. For single simple values, use attributes instead.
- Identify the two Classes that participate in the relationship.
- Add an association between those Classes.
- Name each association end so that the role is clear when read from its Class.
- Save the model and use Validation to confirm that the model has no errors.
For example, an association between Person and Book can describe which books belong to a person. The association connects the two Classes; the end names describe each Class's role in that connection.
Name both association ends
Every association has two ends: one at each participating Class. Give the ends descriptive names that explain the relationship from each side.
| Relationship | Example end names | Meaning |
|---|---|---|
| Person related to Book | Books and Owner
|
A person has related books, and a book has an owner. |
| Person related to Person | Teacher and Pupil
|
A person may be a teacher to other people, and may be a pupil of other people. |
Choose names that describe the role, not only the Class name. In the second example, both ends use the Person Class, so names such as Teacher and Pupil distinguish the two roles.
Associate a Class with itself
You can create an association whose two ends refer to the same Class. This is useful when objects of one Class have different roles in relation to other objects of that same Class.
For example:
- Create or select the
PersonClass. - Create an association from
PersontoPerson. - Name one end
Teacherand the otherPupil. - Add a code comment to the Class if needed to record the purpose of the relationship.
The result models a teaching relationship without creating separate Teacher and Pupil Classes. Both roles are still persons; the association end names explain how they are related.
When to use an attribute instead
An attribute has a simple type and holds one value, such as a name. An association models related objects and can handle lists of values.
For example, use an attribute such as Name:String? for a person's name. Use an association when the person must be related to Book objects or to other Person objects.
See single attributes for attribute notation and options.
Before you continue
The participating Classes must exist before you create the association. You can organize Classes in Packages and document the purpose of each Class with its code comment.
