Association and Inheritance

Kritika gupta
2 min readJul 14, 2020

--

During our code experiment, we usually use some or all of the OOPS paradigm sometimes knowingly or sometimes unknowingly. Terms like association, inheritance, aggregation, composition sometimes seems confusing. So, here comes there definition, difference and impact of usage.

There is very small difference between the two syntactically but programmatically it makes huge difference.

Both of them are used to provide code re-usability.

Inheritance

Inheritance makes use of Is-A relationship between classes.

Example — A chair is a furniture. So, If there are two classes Furniture and Chair. We need to provide Is-A relationship here and Chair class must extend Furniture class. Now, all the features in Furniture class can be reuse in Chair class. We don’t need to write them seperately for Chair class.

Association

Association makes use of Has-A relationship among classes

Example — A Chair has a shape, color, mattress etc. So, there will be 03 classes Shape, Color, Mattress which may have their sub-classes. We need to provide Has-A relationship. There must be member variable of Shape, Color and Mattress inside Chair class.Now, if chair has sub classes too, we don’t need to write separate shape, color classes for all of them. We can reuse existing classes.

Hence, from definition Association paradigm needs minimum two classes. We will refer them as Container Class and Reference Class from now on wards

Note — Is-A relationship is achieved by using extend or implement keyword. Has-A relationship is achieved by creating a member variable of depending class inside dependent class.

Association has 02 types -

(1)Aggregation — When Reference Class can coexist without Container Class, such pattern is called Aggregation. In aggregation, Reference Class doesn’t destroy even if Container Class get destroyed.

Example — As per above example, Shape and Color are aggregated to Chair Class. But as Shape and Color can also be used in other type of furniture like table, they must be aggregated. If Chair Class destroyed, they must exist.

(2)Composition - When Reference Class can not coexist without Container Class, such pattern is called Composition. In composition, Reference Class get destroyed if Container Class doesn’t exist.

Example — As per above example, Mattress Class is composed to Chair Class. Mattress is specific to chair, doesn’t used in Table. Hence, if there is no Chair class, there is no meaning of having mattress class.

Difference Between Inheritance and Composition (Association)

Inheritance vs Composition

--

--

Kritika gupta
Kritika gupta

Written by Kritika gupta

Fertile minded Web Application Developer . Love to explore JavaScript,Angular,Java and looking to increase work productivity. Developer @ Xoriant Solutions

No responses yet