Provide Best Programming Tutorials

Is-a & Has-a Relationship In Java

Aggregation is a special form of association that represents an ownership relationship between two objects. Aggregation models has-a relationships. The owner object is called an aggregating object, and its class is called an aggregating class. The subject object is called an aggregated object, and its class is called an aggregated class.
We refer aggregation between two objects as composition if the existence of the aggregated object is dependent on the aggregating object. In other words, if a relationship is composition,the aggregated object cannot exist on its own. For example, “a student has a name” is a composition relationship between the Student class and the Name class because Name is dependent on Student, whereas “a student has an address” is an aggregation relationship between the Student class and the Address class because an address can exist by itself. Composition implies exclusive ownership. One object owns another object. When the owner object is destroyed, the dependent object is destroyed as well. In UML, a filled diamond is attached to an aggregating class (in this case, Student) to denote the composition relationship with an aggregated class (Name), and an empty diamond is attached to an aggregating class (Student) to denote the aggregation relationship with an aggregated class (Address), as shown in Figure below.

In Figure above, each student has only one multiplicity—address—and each address can be shared by up to 3 students. Each student has one name, and the name is unique for each student.

An aggregation relationship is usually represented as a data field in the aggregating class. For example, the relationships in Figure 10.6 may be implemented using the classes in Figure below. The relation “a student has a name” and “a student has an address” are implemented in the data field name and address in the Student class.

 

Aggregation may exist between objects of the same class. For example, a person may have a supervisor. This is illustrated in Figure below.

In the relationship “a person has a supervisor,” a supervisor can be represented as a data field in the Person class, as follows:

public class Person {

// The type for the data is the class itself

private Person supervisor;

...

}

If a person can have several supervisors, as shown in Figure a, you may use an array to store supervisors, as shown in Figure b.

Leave a Reply

Close Menu