In: Computer Science
Explain what composition is and how to use it.
Answer)
The composition is one of the many features of the object-oriented
programming languages such as Java. The composition allows is to
describe a class which references on or more than one objects which
are in the other classes, for the instance variables. Composition
allows us to have a has-a relationship between objects. Thus using
this we can reuse the existing code, and also change the
implementation of a class.
The composition is done using simple objects creation and then
re-using the code in the other class in the current class. Thus
using this the other class code is not affected and also also the
code can be re-used in the current class. This should be used in
the approach when the classes relationship depicts the has-a
relationship and thus we should use composition rather than
inheriting the entire class. Thus using this the client class code
or anything does not need to be changed, and we can have the
current class bear the change and also reuse the code.