Monday, 11 April 2016

Inheritance vs. Composition vs. Aggregation


Both inheritance and composition allow you to place sub-objects inside your new class.

Inheritance v/s Composition
  • Inheritance is is arelationshipUni-directional
    Used by extends keyword
    Example : House is a Building. But Building is not a House.
  • Composition is has arelationshipUsed by instance variables that refer to other objects.Example : House has a Bathroom. (Incorrect to say, "House is a Bathroom")The class House will have an instance variable, which refers to a Bathroom object.


When to use or not ?
  • Inheritance should be only used when subclass ‘is a’ superclass.
  • Don’t use inheritance just to get code reuse.
    If there is no ‘is a’ relationship then use composition for code reuse.
    Overuse of implementation inheritance (uses the “extends” key word) can break all the subclasses, if the superclass is modified.
  • Do not use inheritance just to get polymorphism.
    If there is no ‘is a’ relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse.


Aggregation vs. Composition
  •  Aggregation and Composition both comes under Association.

  • Aggregation is a part of a whole relationship where a part can exist without a whole.
  • Example : A line item is a whole and product is a part.
    If a line item is deleted then corresponding product need not be deleted.
  • Weaker relationship
  • Composition is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted.
  • Example : An order is a whole and line items are parts.
    If an order deleted then all corresponding line items for that order should be deleted.
  • Stronger relationship

No comments:

Post a Comment

Note: only a member of this blog may post a comment.