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?
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:
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".
If class D
inherits from B
, it means that D
specialises a more general concept B
:
B
(without need to repeat them in the diagram), B
, andB
differently. 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):
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
:
B
object that owns it. This is why we sometimes speak of a "has a" relationship; 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):