DEV Community

Zubair Maqsood
Zubair Maqsood

Posted on

The Basics of Object-Oriented Programming (OOP) - Part 1

If you look at the Wikipedia definition of OOP, it says

Object-oriented programming is a programming paradigm based on the concept of "objects," which can contain data, in the form of fields, and code, in the form of procedures.

This is a really confusing definition for something that can be explained in simple terms. It did get one thing right. OOP is a programming paradigm, arguably one of the most well-known programming paradigms. There are other paradigms such as Procedural and Functional Programming, but that's a story for another day.

In my own words, OOP is a way of writing programs by using the idea of “objects” which have associated data and method within them that essentially describe and explain the behavior of those “objects”. We use a class as a blueprint to create objects.

A lot of programming languages support OOP, such as JavaScript, Python, and Ruby, behind the scenes of each language, the functionality might vary but fundamentally, when dealing with OOP, we use the same 4 "pillars" which are core to the concept. These pillars are Abstraction, Encapsulation, Inheritance, and Polymorphism.

For this article, I am going to use JavaScript to explain the concept of OOP. Let's say we wanted to represent a Person in terms of code. I have the option and luxury of creating multiple person objects which have their own individual name, job, height and weight properties. But that all becomes repetitive. I want a way to quickly and efficiently create or instantiate a Person object without hardcoding everything. This is where the keyword class comes into play.

You can think of a class as a sort of a "blueprint" to create an actual person object. This is how it would look like in code.

Alt Text

In the above example, I have instantiated a new Person object called alex, where I gave that person properties within the constructor function, such as name, job, weight, and height. Two crucial aspects at this point are the constructor() function and the this keyword.

I am not sure about other languages but in JavaScript, the constructor() function holds all the properties within the Person class. So when we create a new Person, the constructor function is called, which actually creates the new Person object. Another important thing is the this keyword. It gets a bit complicated, but ultimately, it makes sure that whatever values you pass in to create a new Person, it makes sure that it is associated to that Person only.

Top comments (0)