Aggregation

When an object contains another object in its body, the relationship between them is called aggregation. This is a loosely-coupled relationship between two objects, in which one object is not completely dependent on the other. Take a look at the following examples:

  • A room has a chair
  • A garden has a plant
  • A dog has a master

This relationship is called a has-a relationship because one object has another object. We cannot say that the plant is a garden, but we can say that the garden has a plant. An object can have a relationship with more than one object:

  • A garden has many plants
  • A company has employees
  • A room has chairs

In this relationship, both objects are loosely coupled. This means that if one object is removed from the other object, both objects can maintain their state. Take a look at the following class diagram of aggregation:

A room contains many objects, including beds and chairs. If we take the chair out of the room and put it in the garden, both the room and the chair will keep their functionalities, or if we remove a plant from the garden and put it in the living room, it would not affect the functionalities of other objects.

Let's consider another example. Nowadays, many people have pets. Some just have one and some have several. The relationship between the pet and the owner is aggregation; both the pet and the owner can live separately as well as together:

class Pet(val petname:String, val breed :String, var owner : Owner?){

fun displayInfo(){

println("Pet name is $petname, its breed is $breed")

if(owner != null) {

println("and its owner name is ${owner?.name}")

}
}
}

class Owner(val name:String, var age: Int)

fun main(args: Array<String>) {

val bob = Owner("Bob", 35)

val cat = Pet("Catty", "Ragdoll", bob)
cat.displayInfo()

val dog = Pet("Doggy", "Golden retriever", null)
dog.displayInfo()
}

Execute the code and verify the output:

In this example, we have the Owner class, which has a name and age. We also have the Pet class, which has three properties: name, breed, and a nullable owner class object. The cat object of the Pet class contains all information, including its owner, but the dog object does not have any owner. The displayInfo() function of the Pet class verifies whether a pet has an owner. If it does, it will display the details of the owner on the screen. Otherwise, it will skip this information. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.247.53