1

Here is the definition of whole-part composition. http://en.wikipedia.org/wiki/Object_composition And here is the inheritance. http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29

I have encountered a question today and I can not solve. Assume that we have a software plan about a software that we are about to build. My question is, in which circumstances existing inheritance relation between two class turn into composition? It sounds weird, but I can not answer it. Thanks in advance.

tahasozgen2
  • 148
  • 1
  • 1
  • 9

1 Answers1

0

Composition (has-a) and Inheritance (is-a) are two distinctly different concepts. There is however a particular situation when the is-a turns into a has-a. Consider

class MyItemList publicly inherits Vector<MyItem>...

This is a clear case of MyItemList is-a Vector. It has all the properties of a Vector, it can be used as a Vector of MyItems . Everybody can use an instance of MyItemList as a Vector.

Now consider

class MyItemList privately inherits Vector<MyItem>...

MyItemList is not telling anyone it is a Vector. Nobody can use MyItemList as a Vector. It has all the properties of a Vector (has-a Vector) but doesn't tell anyone about it.

This is effectively a has-a relationship. The only difference is MyItemList does not refer to the vector by an attribute/field/member, but rather by this (or whatever selfreferential keyword your language use).

The language of your choice has to have a mechanism to declare inheritance as non-public of course.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67