Composition vs Inheritance in Coding

Martin Valdivia
Analytics Vidhya
Published in
3 min readApr 15, 2020
Photo by Christopher Gower on Unsplash

These are 2 ways to construct objects and build classes within object orientation across programming languages.

Composition

Composition is the idea that an object within our program can have something. For example, one object has access to use another object within the program.

Unlike Inheritance, when creating classes using composition you are able to use a class object within another class object.

In the pictures below we have two classes which are Song and Album.

Song class with :Title and :Duration
Album Class with :name and :songs

We will fill up the album with multiple Song objects to create a song list within a new array using the song class and the attributes we gave it in the 1st picture.

The attributes in this example are random. We just needed to create song objects

Now it’s time to create a new album object!

We will replace the songs attribute we gave the Album Class in the 2nd picture with the song list we have just created while making a new album object.

my_album = Album.new(“Martin’s album” , songs_list)

Now we have Song objects within an Album object and that is known as composition.

Inheritance

Inheritance is used when you have an object that is the same as another object but a more specific type.

For example a bass guitar is still a guitar but a more specific type so we would use inheritance to have the bass inherit attributes from the guitar.

Here are 2 classes, one for guitar and one for bass

The BassGuitar class inherits the Guitar class because it is the same but a more specific type. The Bass will inherit all the functionality and attributes and this is done with the < symbol on line 57 between the class and the class it is inheriting.

That is the difference between Composition and Inheritance.

One allows you to have an object within another object and one allows you to inherit the attributes from a more general class of the same type.

--

--