What is composition in Java

4.3 Relationships between objects

In Figure 4.10 we have already shown a number of relationships between characters in Greek mythology. You saw that objects can have a wide variety of relationships to one another.

When speaking of relationships in the object-oriented world, there are basically three types of relationships:

Relationships between classes and objects

  • Relationships between classes and objects We got to know such a relationship, the classification, in Section 4.2.1. The classification describes a relationship between a class and its instances. The object Plato, for example, has such a relationship with the class man, because Plato is a man (or a copy of the class man). You can see this relationship by marking in Figure 4.21.

Relationships between classes

  • Relationships Between Classes Because Plato is a man and a man is a person, Plato is mortal, for every person is mortal. So there is a relationship between the class of mortal objects and the class Person - the class Person is a subclass of the class Mortal. And since every man is a person, the Person class is an upper class of the Man class. In Figure 4.21 this relationship is shown by marking.
    • We will deal with the relationships between the superclasses and subclasses in Section 5.1.1, "Hierarchies of Classes and Subclasses".

Relationships between objects

  • Relations between objects Aristotle had a teacher, Plato, and a well-known student, Alexander the Great. These are examples of a relationship between concrete objects to which we will now turn. In Figure 4.21 you can see these relationships by the markings and.

Figure 4.21UML representation of Aristotle's relationships

Association, Aggregation and Composition

Relationships between different objects are generally called association. [Although in UML an association is represented as a line between the class boxes, an association is a relationship between objects - the instances of those classes. An example of a relationship between classes would be generalization, to which we will address in Section 5.1.1, "Hierarchies of Classes and Subclasses". ] There are also special forms of associations.

Relationships between an object and its parts are called aggregation or composition. The distinction between aggregation and composition is quite subtle and often depends only on the developer's perspective. We will take a closer look at aggregation and composition in Section 4.3.8.

Associations between objects

Let's see what we can say about the associations between objects below.

An association always has a semantic meaning. Two or more objects can have different relationships to one another. Just as in life two people can have a parent-child relationship and, independently of that, a supplier-customer relationship. [We will not devote ourselves to all the details of the capabilities of UML in this book; you can find a more in-depth description in [Kecher 2006]. ]

Associations in UML

In UML class diagrams, possible associations between instances of two classes are shown as a line between the class boxes. If there is a relationship between instances of exactly one class, it is represented by a line that both begins and ends in the box for the class.

If you represent individual objects in a UML diagram, you can represent an existing relationship between these objects as a line between the object boxes. Such a representation of an existing relationship between two individual objects is called a link.

The meaning of the relationship is most often expressed by the name of the relationship. In UML, the name of the relationship is represented as text near the line.

4.3.1 Roles and direction of an association

The relationships between objects are mostly not symmetrical, which means that each object has a different role in the relationship. We can say that Zeus lives on Olympus, but not Olympus on Zeus. So the name of a relationship has a direction.

Roles in UML

In UML class diagrams15  the roles of the objects are specified as text in the vicinity of the respective class. The reading direction of the description of the relationship is indicated by a small triangle.

Figure 4.22Role and direction of an association

4.3.2 Navigability

Another important property of a relationship is its navigability. Let us assume that there is an association between the instances of the Company class and the Person class. The company can list all the people it sends advertisements to. However, a person does not have a list of companies that are bothering them with advertising. We say that the association sends advertisements in the direction of company-person, but not in direction of person-company. Navigability is mostly specified in the design models, while navigability rarely plays a role in the analysis models.

Figure 4.23Navigability of an association

Navigability in UML

In UML, a relationship that is only navigable in one direction is indicated by an arrow at the end to which we can navigate. If a relationship can be navigated in both directions, this is usually represented by the absence of arrows, but it is also possible to use a double arrow.

4.3.3 Multiplicity

The multiplicity of a relationship indicates how many objects of the respective type can be in this relationship.

Files in the file system

Take, for example, a model for a simple file system in which each file is always in exactly one directory. However, a directory can be empty or it can contain one or more files. The range for the possible or necessary number of objects in such a relationship is referred to as the multiplicity of this relationship.


The multiplicity of a relationship between classes determines the possible number of instances involved in the relationship.

We speak of the multiplicity of a role in the relationship if we only consider one of the classes involved and their role in the relationship.

In UML, the multiplicity of a class in a relationship is specified as a listing of the possible number of instances. This indication is simply presented near one end of the relationship at the class in question. Intervals are given as "min .. max". A star means "any number". The interval "0 .. *" can also be specified as "*".

In addition to the multiplicities in a relationship, there is also the pure multiplicity of a class. This defines how many copies of this class can or must exist at all. The multiplicity of a singleton class16 is usually 0 ... 1, which means that a maximum of one copy can exist.

Figure 4.24 illustrates the concept of multiplicity and its representation in UML.

An association is shown at marking between instances of the City class and the Country class. The association is represented by a line that starts at the city class and ends at the country class. According to our model, a city lies in exactly one country. There must be at least one city in a country, but there is no upper limit to the number of cities. The multiplicity of the role city in the relationship described is 1 .. *, the multiplicity of the role country is exactly 1. The multiplicity of the entire relationship is thus 1 .. * to 1.

Figure 4.24Multi-valued relationships in UML

Another example is the parent-child relationship shown at marker in Figure 4.24. This relationship exists between instances of the Person class. Such relationships between instances of the same class are called reflexive. The multiplicity of the child role is * (i.e. any number), because there are people who have no children and people who have one or more children. But what about the multiplicity of the role of parent? For example, if we were to write a genealogical application, one would spontaneously say that it is 2, because every person has exactly one biological mother and exactly one biological father. In the figure, however, you can see that the multiplicity of the role parent is modeled as 0..2.

This is because in the practical use of the relationship you run into a logical problem if you ask for each person to also know the parents who belong to them. Since it would be required for each inserted parent (including another person) that the parents are already known for them too, if you try to create a consistent database, you will get into a non-terminating recursion. Therefore, the relationship is modeled in such a way that the parents of a person can simply be unknown, i.e. the role of parent receives the multiplicity 0..2.

Possible multiplicities

In the example you have already seen some of the possible multiplicities. Most often you will encounter relationships with the following multiplicities in models:

An object is related to

  • exactly one other object.
  • no or any other object.
  • at least one other object.
  • any number of other objects.

But there can certainly be relationships with other multiplicities. For example, in the tennis match-player relationship, also shown in Figure 4.24, the multiplicity of players is two or four.

Cardinality and multiplicity

In UML, a clear distinction is made between the multiplicity and the cardinality of a relationship: The multiplicity defines the possible cardinalities of a relationship, usually by specifying the minimum and maximum cardinality.

The actual cardinality of a relationship can only be specified for specifically known objects. For example, there are exactly 2076 cities in Germany. The cardinality of the role city in this relation would be 2076. However, the associated multiplicity of the role is 1 .. *. This simply describes the possible cardinalities, of which 2076 is also one.

The conceptual separation between multiplicity and cardinality is not always as clear as it is defined within the UML. In the case of the models used in the area of ​​relational databases in particular (e.g. entity relationship diagrams), the term cardinality is often used analogously to multiplicity in UML17.

Value relationships

If the upper bound of the multiplicity of a relationship is greater than 1 (e.g. *), i.e. the relationship is multi-valued, we can think about the structure of the objects at the multi-valued end of the relationship. When the objects in this relationship have a defined order, the relationship is said to be in order.

Another question we can ask is whether an object can be listed multiple times in the relationship. A team can consist of several players, but a specific player cannot appear more than once in a team. A travel route can lead through several cities, whereby a city can be traversed several times in a route.

Multi-valued relationships as a set

Unless otherwise specified, we usually understand a multi-valued relationship as a set without a defined order in which an object can only occur once. Once the order has been defined, the {ordered} or {ordered set} restriction applies to the relationship, depending on whether an object can occur more than once. There is also the case in which an object can appear several times, but the order is still irrelevant. This type of relationship is called a bag in English and a basket in German. An example of such a relationship would be the list of subscribers to a magazine, if the publisher has not sorted out duplicates. A customer can have multiple subscriptions to a magazine, but the order in which the magazine is sent is irrelevant.

Limitations of relationships in UML

In UML, other information can also be specified in a relationship. The restrictions are indicated in curly brackets. In addition to the restrictions {ordered} or {bag}, you can specify, for example, whether a relationship is acyclic or represents a hierarchy.

Figure 4.25Additional information on relationships in UML

4.3.4 Qualifiers

Sometimes you can make a more precise statement about the multiplicity of a relationship. For example, a person can have multiple spouses in the course of their life. But at one point in time, at least in our culture, a person can have at most one spouse. Another example is the relationship between a company and its customers. A company can have many customers, but with a customer number it can uniquely identify one of its customers. A company has exactly one customer per customer number.

We can express this information about the multiplicity of a multi-valued relationship by specifying the qualifiers. With the help of a qualifier, certain objects can be selected from many objects at a multi-valued end of a relationship.

Figure 4.26Qualifiers of relationships in UML

In the relationship marriage, for example, a point in time is a qualifier that enables us to pinpoint a specific spouse of a person who has been married several times. The customer number is in turn such a qualifier in the relationship between a company and its customers.

Qualifiers in UML

In UML diagrams, the qualifiers are shown as boxes at the end of the relationship from which we navigate with the help of the qualifier. The names of the qualifiers can be indicated either in the box or near it. At the other end of the relationship, one then states the multiplicity of the qualified relationship.

4.3.5 Relationship classes, attributes of a relationship

Now let's look at the job relationship between the Person and Company classes.

Figure 4.27Relationship class in UML

There are people without a job, but one person can also have several jobs. A company (at least in our model) always has at least one employee, be it the entrepreneur himself. The multiplicity of the role of employer is 0 .. *, that of the role of employee is 1 .. *.

Although the order of the employees does not matter and we have therefore modeled the relationship in the direction of the company-person as a set, it is important to know what function an employee has in a company. And what is also important, at least for most of us in such a relationship, is how high the salary [We mean both wages and salaries here. ] of a person in a company.

Which class can we assign this information to? Obviously, we cannot assign the attributes function and salary to the company class, because then all employees would have to have the same function and earn the same salary.

If we were to assign these attributes to the person class, each employee could have their own function and salary, but the function and salary would have to be the same in every company. In addition, these attributes would have no meaning for a person without a job. [If we were to develop a personnel management system for an employer, we could definitely assign the attributes function and salary to the employee class. A person can have several jobs, but this would not be relevant for our system. We would not manage the jobs that an employee has at other companies. ]

Association class

The solution to our task is to assign the attributes neither to the company nor to the person class, but to the job relationship itself. In this case, one speaks of an association class or a relationship class.

Association classes in UML

In UML, an association class is represented as a class that is connected to the relationship line with a dashed line.

We can always model an association class as a normal class. It is a question of the comprehensibility of the models which alternative one chooses. A possible alternative is shown in Figure 4.28.

Figure 4.28Alternative representation of a relationship class

4.3.6 Implementation of Relationships

Relationships differ among other things in their multiplicity, their navigability; the polyvalent ones can be ordered or disordered; an object can occur once or more than once. So there are so many types of relationships. For this reason there are no special constructs for the implementation of the relationships in the common programming languages.

Implementation of relationships

Instead, in the case of single-valued relationships in the object from which the relationship can be navigated, pointers or references that point to the other object are mostly used.

A bilateral navigable relationship is most often implemented by two pointers or references that have to be kept in sync with the program.

The multi-valued relationships are implemented in different ways. Arrays, lists, quantities or other container constructs that are available in the respective programming language or that you implement yourself are used.

Relationship classes are implemented as ordinary classes.

Listing 4.12 shows the implementation of various relationships in Java.We show a possible implementation of a bilateral navigable quantity relationship between person and address. One person can have several addresses, and one address can be used to find several people.

class Person {private Set
addresses = new HashSet
(); // Here we manage a direction of the relationship // Person-Address: public void addAddress (Address address) {if (addresses.contains (address)) return; adresses.add (address); address.addPerson (this); // maintain the other direction} ...} class Address {private Set people = new HashSet (); // Here we manage a direction of the relationship // Person-Address: public void addPerson (Person person) {if (people.contains (person)) return; people.add (person); person.addAddress (this); // maintain the other direction} ...}

Listing 4.12Mapping of relationships to classes

4.3.7 Composition and aggregation

So far we've looked at the relationships between different objects. But an object itself can be complex in structure, and we can model the relationships between the object and its parts. We differentiate between composition and aggregation.

Both the composition and the aggregation are part-of or consists-of relationships. For example, we can model that an order consists of the order lines or that a soccer team consists of its players.

Difference between aggregation and composition

An aggregation is different from a composition

  • in the number of composite objects that an object can be part of, and
  • in the life of the assembled objects and their parts.


We speak of an aggregation when an object can be part of several composite objects. In this case we call the composite objects aggregates. The service life of the parts can be longer than the service life of the units.

An example of aggregation is the relationship between a team and its players. A person can play in several teams, and if a team is dissolved, it does not mean the end for their ex-players in the vast majority of cases.


In a composition, a part can only ever be contained in exactly one composite object, and the lifetime of the composite object always corresponds to the lifetime of its components. The compound object is referred to here as compound.

An example of a composition is the relationship between an order and each line of the order. An order line belongs to exactly one order, and if the order is deleted, all of its items are automatically deleted as well.

Composition and aggregation in UML

In modeling, it is often the case that a class plays the role of part in several compositional relationships. Each instance of this class can only have one such relationship. In the models, these relationships can be marked with the condition {xor}.

If the relationships can only be navigated in the direction of the compound component, the explicit specification of the condition {xor} is usually not necessary.

In the class diagrams in UML, the aggregation is represented by an empty diamond at the end of the aggregate. The composition is represented by a filled diamond at the end of the compound.

Figure 4.29Aggregation and composition in UML

Alternatively, the composition can also be displayed as shown in Figure 4.30.

Figure 4.30Various alternative representations of the composition

Use of composition and aggregation

The decision whether to model a relationship as an aggregation, a composition, or a simple association is often difficult because there are no hard and fast rules by which we can distinguish which of the options is appropriate. The semantic meaning is only vaguely defined in UML; one speaks of a modeling placebo. But as we know, placebos work. So let's try to come up with a few guidelines that will help us decide which variant to use.


Using composition is a very good way of expressing that a relationship between objects of the same class is hierarchical. Good examples are organizational charts or file systems.

Lifespan and persistence

Another piece of information that can be expressed by modeling a composition is the behavior of the objects when deleting or saving the compound. Since the compound word consists of parts that only exist as parts of the compound word, they are deleted or saved with the compound word. However, these semantics affect the dynamic aspects of the models, and the class diagrams are intended to represent the static facts.

Data structure

A useful use of a composition is to model the classes in C ++. The structure of the memory in which the data of an object is stored is explicitly programmed there. Whether an object contains its parts directly or whether it contains pointers to other storage areas is a fact that is excellently expressed using the composition. However, this is not a general specification of UML, it is only a suggestion that can be followed when graphically representing the C ++ classes in a UML class diagram.

Discussion: composition and aggregation

Bernhard: How do I actually decide whether to model a relationship as a composition, aggregation or simply as an association?

Gregor: We have already given some pointers. Above all, the technical criterion, whether the referenced components should be deleted together with another object, strongly suggests a composition.

Bernhard: What if that cannot be decided so precisely at the time of modeling?

Gregor: When applied carefully, the composition and the aggregation can contribute to a better understanding of the model. Sometimes it's just natural to say that an object is made up of other objects. But we shouldn't waste too much thought and time on the modeling decision. Every composition and every aggregation can be represented simply by an association with corresponding restrictions and the indication of navigability and multiplicity.

4.3.8 Attributes

In addition to its functionality and relationships to other objects, an object has attributes - properties that describe the object and data that the object manages. In Section 4.1.1 we already introduced how properties of objects are described.

Strictly speaking, attributes of an object correspond to the components of this object in different compositional relationships. Being an attribute and being a component are two interchangeable ways to describe the same concept. Therefore, the notation for the representation of the attributes in UML corresponds to the compact notation for the representation of the composition.

The same applies to attributes as to composition: They can be single or multi-valued. If they are multivalued, the order of the values ​​may or may not be relevant. A value can appear more than once, or each value must be unique.

The multiplicity of the whole is exactly the same for attributes as for composition. The navigability for the attributes is almost always in the direction of compound object-attribute. If at some point another type of navigability is required, we recommend that you model this relationship not as an attribute, but as a composition.

4.3.9 Relationships between objects in the overview

In Figure 4.31 you can see the UML display options for relationships between objects in the overview.

Figure 4.31Representation of relationships between objects in UML

your opinion

How did you like the Openbook? We always look forward to your feedback. Please send us your feedback as an e-mail to [email protected]