Composition
•
Composition is a strong type of Aggregation (strong association).
•
Part- whole relationship where part cannot exist without a whole
• The life cycle of child is
fully dependent on parent object, if parent object deletes all child object
will also be deleted
Relationship
between House and Rooms. House can contain multiple rooms, there is no
independent life of room and if we delete the house, room will be automatically
deleted.
final class Car {
private final Engine engine;
Car(EngineSpecs
specs) {
// lives within car
object- Engine cannot exist without car
engine = new Engine(specs);
}
void move() {
engine.work();
}
}
Here
the Engine is completely encapsulated by the Car. There is no way for the
outside world to get a reference to the Engine. The Engine lives and dies with
the car.
•
Aggregation is a weak association
•
Part- whole relationship where part can exist without a whole
Example
1:
final class Car {
private Engine engine;
void setEngine(Engine
engine) {
this.engine = engine;
}
void move() {
if (engine != null)
engine.work();
}
}
Example 2:
public class Person {
private Address address;
public Person(Address
address) {
this.address = address;
}
}
Here
the outside world can still have a reference to the Engine or Address and it
can exist without Car or Person respectively.
• Association is the
relation between two objects. In other words its connectivity between two
objects. Aggregation and compositions are form of association.
No comments:
Post a Comment