There are various relationship types that exist in java called Association, Aggregation, and composition.
Association represents the unidirectional or bidirectional relationship between two classes. If the Customer places an order, then this is a unidirectional association.
In Aggregation, the based object is standalone and can exist even if the object of the control class is dead. E.g. the association between Car and Wheel is the aggregation.
Aggregation vs composition Summary
- Aggregation and Composition are a special type of association and differ only in the weight of the relationship.
- Composition is a powerful form of “is part of” relationship collated to aggregation “Has-A”.
- In Composition, the member object cannot exist outside the enclosing class while same is not true for Aggregation.
Inheritance:
Inheritance is basically Is-A relationship. We can achieve inheritance with the help of extends keyword
- Pros: Code re-use, easier to understand
- Cons: Tightly coupled, fragile, prone to be abused by developers
Composition:
- Pros: Code re-use, great Flexibility, Loose coupling
- Cons: A little harder to understand, complex design structure
Inheritance (IS-A relationship):
Class Vehicle{
}
Class Car extends Vehicle{
{
-->> Car IS-A Vehicle (Two classes are tightly coupled)
Association (HAS-A relationship):
Example 1:
Class Student{
String name;
int rollNo;
}
-->> Student HAS-A name
-->> Student HAS-A rollNo
Example 2:
Class Engine {}
class Car{
Engine e = new Engine();
}
-->> Car HAS-A Engine (Two classes are loosely coupled)
Car HAS-A musicPlayer -->>Weak bonding between classes -->>Aggregation
Car HAS-A engine -->> Strong bonding beween classes -->>composition
No comments:
Post a Comment