[Solved] Object in one class is the instance variable in the other. Relation between those classes?


The two classes are certainly related i.e. they have an Association. But, the nature of their relationship could either be an Aggregation or Composition. To give you an example and thereby explain how it’s different than Inheritance; consider the following classes:

  • Shape (Base class; can be abstract)
  • Circle, Triangle, Square etc. (Derived classes)
  • Line, Colour (Classes used in aggregation or composition)

Any of the derived classes: Circle, Triangle, Square “IS-A” Shape as well. This is Inheritance where the subclass like Circle extends Shape superclass. All public & protected attributes (like area) and behaviour (say, move()) are inherited and accessible to the child classes.

Now, each of these shapes would be composed of Line(s) and would have a Colour i.e. actual instance of these classes would be present as attributes (properties) inside the shape class objects.

This is known as a “HAS-A” relationship because a Shape, say, a Square has-a Colour and four Line(s). This relationship can be further observed in the following two forms:

  • Aggregation (is a directional association)
    Here, Shape subclasses and Colour have an aggregation. This relationship is many-to-one i.e. a shape can have only one colour and one or more shapes can have the same colour.

  • Composition (is a stronger form of aggregation)
    Here, Shape subclasses and Line(s) have a one-to-many composition. The difference is that the lifetime of a contained object is dependent on its container.

For example, if a Triangle is destroyed, it’s Line(s) get destroyed as well. On the other hand, if it was painted red, the corresponding Colour object still remains alive since as part of a many-to-one relationship it may possibly be referenced by other shape objects as well.

References :
Has-A relationships (Wikipedia)
Composition over Inheritance (Wikipedia)
Prefer composition over inheritance? (StackOverflow)
Aggregation vs Composition vs Inheritance vs Association vs Dependency

solved Object in one class is the instance variable in the other. Relation between those classes?