Tags

Feb 22, 2012

Inheritance versus composition

IS-A is tied to inheritance of one class by another class and HAS-A is tied to member instance variable of another class.

1) Both IS-A and HAS-A offer code reuse
Both result in the re-use of code already written in another class.

2) Run time polymorphism can be achieved with IS-A and not with HAS-A
Since IS-A is tied to inheritance so run-time polymorphism is achievable through IS-A relationship.

3) IS-A results in increased coupling between two classes but HAS-A usually draws a line on coupling
IS-A should be used when cohesion is to be increased but HAS-A has no visible effect on cohesion

4) The container class manages the lifecycle of contained class’s object in HAS-A relationship but the super class doesn’t play any role in the lifecycle of sub class’s object in IS-A relationship.

5) HAS-A relationship is closely related to another term named as Delegation.
When the container class invokes some method on the contained class’s object then the container is said to have delegated the call to container object.

6) IS-A can be visualized as a parent-child or vertical relationship.
HAS-A can be visualized as sibling or horizontal relationship.
Use IS-A relationship for closely related classes with sub class being more specific version of super class and use HAS-A relationship for possession kind of relationships

No comments:

Post a Comment