Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composition vs. Inheritance

For a UML Class Diagram, if a class A has a composition relationship with another class B, does it work like inheritance? I know that the class A cannot exist without class b but does class A inherit the attributes and methods from class B?

like image 354
Binaya Thapa Magar Avatar asked Sep 06 '25 03:09

Binaya Thapa Magar


1 Answers

Composition over inheritance

In OO design, a common advice is to prefer composition over inheritance. This might mislead to think that there is a relation between these two different concepts:

  • Inheritance is about a relation between classes.
  • Composition is a about relations between objects of classes.

Even more misleading: the "composition" used in the general OO literature corresponds in general to a simple UML association and is not to be understood as restrictive as the UML "composition".

Inheritance is about generalisation and specialisation

If class D inherits from B, it means that D specialises a more general concept B:

  • It has all the properties and operations of B (without need to repeat them in the diagram),
  • It can have additional properties and operations that are not relevant for B, and
  • It can perform some operations of B differently.
  • Any object of class D is also an object of class B for its full lifetime. This is why we speak of a "Is a" relationship.

Naive example (just for the illustration):

enter image description here

Composition is about association of objects of very different classes

If class B "composes" (has a composition association with) C, it means that the B object can be associated with different C objects over its lifetime. Anf that objects of class C :

  • always belong to a B object that owns it. This is why we sometimes speak of a "has a" relationship;
  • will not survive its owning B object .

Caution: UML composition is about an exclusive ownership. In the OO literature, the term "composition" often refers to weaker associations without any ownership or even exclusivity.

Naive example (just for the illustration):

enter image description here

like image 172
Christophe Avatar answered Sep 07 '25 21:09

Christophe