Composition

Composition is an advanced form of aggregation, where two objects are highly dependent on each other. In aggression, one object contains the other object, whereas in composition, one object owns the other object. When the object that owns the other is destroyed, the object that is owned is also destroyed. In composition, an object may be composed of small objects. The human body is a good example: a person is composed of a head, arms, legs, and more. Each part of our body is a fully-working object with its own characteristics and behaviors. We can talk, listen, and see using our head, we can walk using our legs, and we can hold different objects using our hands. If a person dies, however, the objects stop working and die as well. A chair is another useful example, as it is made up of different objects including a seat, wooden legs, arms, and a back.

Take a look at the following class diagram of composition:

Let's take an example of a Person class, where the person is an employee of a company. Create a class called Job with the company information, including department and salary:

class Job (val companyName : String, var department : String, var salary : Long)

Create another Person class with three properties: name, age, and a job object:

class Person(val name: String, var age : Int, val job: Job){

fun getSalary() : Long {
return job.salary
}

fun getCompanyName() : String {
return job.companyName
}

fun geDepartmentName() : String {
return job.department
}

fun info(){
println("===================================")
println("Person name $name , age $age")
println("Company Name : ${getCompanyName()}")
println("Department Name : ${geDepartmentName()}")
println("Salary : ${getSalary()}")
println("===================================")
}
}

Create an instance of a job with its required parameters and pass this instance to the Person class object. Use the Job class object in the person class and extract the company, department, and salary information from the job object:

fun main(args: Array<String>) {
val job = Job("Microsoft", "Research and Development", 8000)
val bob = Person("Bob", 35, job)
bob.info()
}

Execute this example and verify the output:

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

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