InterviewSolution
| 1. |
What is the difference between Composition and Aggregation? |
|
Answer» Composition Like Inheritance gives us an 'is-a' relationship. Composition gives us a 'part-of' relationship. Composition is shown on a UML diagram. If we were going to model a car, it would make sense to say that an engine is part-of a car. Within composition, the LIFETIME of the part (Engine) is managed by the WHOLE (Car), in other WORDS, when Car is destroyed, Engine is destroyed ALONG with it. public class Engine { . . . } public class Car { Engine e = new Engine(); ....... }As you can see in the example code above, Car manages the lifetime of Engine. Aggregation As Inheritance gives us 'is-a' and Composition gives us 'part-of', Aggregation gives us a 'has-a' relationship. Within aggregation, the lifetime of the part is not managed by the whole. For Example: Aggregation would make sense in this situation, as a Person 'has-a' Address. It wouldn't make sense to say that an Address is 'part-of' the Person, because it isn't. Consider it this way, if the person ceases to exist, does the address So how do we express the CONCEPT of aggregation in C#? Well, it's a little different to composition. Consider the following code: public class Address { . . . } public class Person { private Address address; public Person(Address address) { this.address = address; } . . . }Person would then be used as follows: Address address = new Address(); Person person = new Person(address);or Person person = new Person( new Address() );Here Person does not manage the lifetime of Address. If Person is destroyed, the Address still exists. |
|