Understanding the basics of Object Oriented Programming as a Beginner

Understanding the basics of Object Oriented Programming as a Beginner

Introduction

In this article, I will be taking you through how you can understand the basics of object-oriented programming as a beginner, this article is divided into two sections for easy understanding and clarification.

SECTION ONE

What Is Object-Oriented Programming?

Object-Oriented Programming is actually a programming paradigm that tells you to divide your code into a different object, and those objects contain fields and methods. When I say fields, I basically mean variables and when I say methods, I basically mean functions that can be connected to each other and you can change the data that is inside them as well.

Why do we really need Object Oriented Programming?

Object-Oriented Programming is helpful when we are creating an entity with common input fields and methods which will be reusable.

Setting up your Editor

I will be using Nodejs throughout this article so that I can see the responses in my code editor's terminal, so I don't need to go to the browser to see the output. If you don't have Nodejs installed on your system yet, you can install it here nodejs.org.

After the installation is complete, Open up your preferred text editor and open the editor's terminal, In my case, I will be using VSCode. Once you open the terminal, type the below code snippet to check the version of the node installed on your computer.

node  -- version

The output should be similar to this

v16.13.2

Once you see something similar to this, then you are good to get started, but the node version you installed might be different from the above snippet based on the time you are reading this article.

Refreshing Javascript Object

You have probably used something like this before, or you are more conversant with objects like this

    const user = {
        name: "Layobright",
        age: 25
    }

To access the value of the name directly from the object, we make use of the dot notation in javascript.

    const user = {
        name: "Layobright",
        age: 25
    }
   console.log(user.name)

To get the output of the above snippet in your terminal, type node (the name of the file) which in my case is node index.js, now press the Enter on your keyboard to see the output.

 Layobright

You can also put functions inside of the object as well, just like the below code snippet

const user = {
  name: "Layobright",
  age: 25,

  getName: () => {
    console.log(`my name is ${user.name}`);
  }

};

user.getName();

Actually, this is not the way that we define objects if you are going to code in object-oriented programming, it is done by creating classes and the reason for that is because it becomes a lot more well structured.

Getting started with OOP

Object-oriented programming allows you to create a different object by using the class keyword, Imagine we want to create a person or something that will have common fields and common methods and we are going to re-use that code as many times as possible.

People might be different, but they will have some underlining similarities like each person having a name, an age, education, and so on...

To create a class, you can just say class and the name of the class just as you can see in the below snippet, note that the first letter of the class name is Capitalized.

    class Person{

    }

After creating a class, you need to make sure that you actually put a constructor, which is the first thing that runs when you instantiate your object.

class Person{
    constructor()
}

Inside the constructor, we will put the variables that are going to come when we instantiate a new person and basically set them so that they are accessible throughout our class.

when creating a person, we want to pass for example a name, age, and education, because these are the things that are different in each person, and also create a function called getName which literally just returns the name property. see the snippet below for clarifications

class Person {
    constructor(name, age, education){

    }
}

However, these three variables that we passed to the constructor are not accessible throughout our class.

Why do we need to use this keyword?

The reason for that is because the variables passed to the constructor when we instantiate the object are not accessible anywhere else in the class, so to make them accessible we make use of this keyword.

Let's try some examples to access the variables without this keyword and also with this keyword for easy understanding.

Accessing the variables without the this keyword

class Person{
     constructor(name, age, education){
         name = name;
         age = age;
         education = education
    }
}

let person1 = new Person("Layobright", 25, "Tetiary")

console.log(person1)

when you run this snippet in your editor, the output of the person1 variable will be an empty object {}

{}

In order to have access to the variables passed to the constructor, this keyword need to come into action just as you can see in the snippet below

Accessing the variables with this keyword

 class Person{
    constructor(name, age, education){
        this.name = name;
        this.age = age;
        this.education = education
     }
}

However the three variables passed to the constructor allow us to create an actual person, so in theory, we can use this object to create different people and to actually instantiate an object or class.

    let person1 = new Person("Layobright", 25, "Tertiary")
    console.log(person1)

when you run the above snippet in your editor, the output will be :

        Person{
            name: 'Layobright',
            age: 25,
            education:'Tertiary'
        }

Here we created a new person with the name, age, and education property of that person. You actually need to use the new keyword in order to create a new person. Basically, you are just saying that you want to instantiate a new version of the Person class.

Now let's create a new person with different properties.

class Person{
    constructor(name, age, education){
        this.name = name;
        this.age = age;
        this.education = education
    }
}

let person2 = new Person('Mark', 23, 'Secondary')
console.log(person2)

when you run the above snippet in your editor, the output will be :

Person{
     name: 'Mark',
     age: 23,
     education:'Secondary'
}

To access the name directly, I can say

console.log(person2.name)

which will return the name value Mark from the object.

Accessing class properties

Accessing the property directly is not something you would like to do if you are designing your project in an Object-Oriented manner, the reason for this is that you don't want to have full access to the fields directly from the outside.

The best way to do this is to create methods inside of your class that basically return the fields.

 class Person {
  constructor(name, age, education) {
    this.name = name;
    this.age = age;
    this.education = education;
  }

  getName = () => {
    return this.name;
  };
}

The major use of this method is just to return the name of the variable instead of accessing the name directly.

Lets create another example to get things clearer

    let person3 = new Person('Steven', 27, 'Tertiary')
    console.log(person3.getName())

The output of the above snippet will return the name property

Steven

Now let us add more data to the person class

 class Person{
        constructor(name, age, education, gender){
            this.name = name;
            this.age = age;
            this.education = education
            this.gender = gender
        }

        getName =() => {
            return this.name
        }

        getAge = () => {
            return this.age
        }

        getEducation = () => {
            return this.education
        }

        getGender = () => {
            return this.gender
        }

    }

    let person2 = new Person('Mark', 23, 'Secondary', 'Male')
    console.log(person2.getName())
    console.log(person2.getAge())
    console.log(person2.getEducation())
    console.log(person2.getGender())

The output of the above snippet will be :

    Mark
    23
    Secondary
    Male

Now we've created an object that can be reused to create a different person.

clap.gif Give yourself a round of applause for completing the section one of this article, I believe you now have a basic understanding of what Object Oriented Programming is all about.

SECTION TWO

Practical examples of OOP

There is a lot more we can do with Object-Oriented Programming, Let's dive in to make it a bit more complex. we can see in section one that we have a very simple class.

So let's assume I want to get the number of people living in the house I built for rent, let's create a house class.

 class House {

 }

Now that the house class has been created we need to create the constructor and add the variables inside the constructor. The question you should ask yourself is, What properties do I need inside my constructor.

We just created a house class, so the house should have

  • The house address
  • The House number
  • Paint color of the house
  • The tenants living in the house
    class House{
        constructor(address, houseNumber, houseColor, tenants)
    }

Let's make the variables added to the constructor accessible in my house class.

    class House{
        constructor(address, houseNumber, houseColor, tenants){
            this.address = address
            this.houseNumber = houseNumber
            this.houseColor = houseColor
            this.tenants = tenants
        }
    }

Now the variables are accessible anywhere in my house class, don't forget we created a person class in section one of this article, we will be making use of the person class as well. Before then, let's create a method for each of the variables added to the constructor.

    class House{
        constructor(address, houseNumber, houseColor, tenants){
            this.address = address
            this.houseNumber = houseNumber
            this.houseColor = houseColor
            this.tenants = tenants
        }

        getAddress = () => {
            return this.address
        }

        getHouseNumber = () => {
            return this.houseNumber
        }

        getHouseColor = () => {
            return this.houseColor
        }

        getTenants = () => {
            return this.tenants
        }
    }

Now that we've created the method for each variable added to the constructor, let's instantiate the house objects from the house class, and pass the properties to the constructor.

    let house = new House('12 jude avenue London',  22,  'Blue',  [ ]  )

Take note of the variable tenants passed to the constructor, which is a list of people living in my house. We need to create a new set of people that will be passed to the tenant's list, so let's bring back the person class created in section one of this article.

THE PERSON CLASS

    class Person {
    constructor(name, age,education, gender) {
        this.name = name;
        this.age = age; 
        this.education = education; 
        this.gender = gender;
    }

    getName = () => {
        return this.name;
    };

    getAge = () => {
        return this.age;
    };

    getEducation = () => {
        return this.education
    }

    getGender = () => {
        return this.gender;
    };
    }

    const person1 = new Person('Layobright', 25, 'Tertiary', 'Male')
    const person2 = new Person('Juliet', 23, 'Tertiary', 'Female')
    const person3 = new Person('Johnson', 27, 'Secondary', 'Male')

Now that we have created three different people, let's instantiate the house object and pass each person to the tenant list

THE HOUSE CLASS

 class House{
        constructor(address, houseNumber, houseColor, tenants){
            this.address = address
            this.houseNumber = houseNumber
            this.houseColor = houseColor
            this.tenants = tenants
        }

        getAddress = () => {
            return this.address
        }

        getHouseNumber = () => {
            return this.houseNumber
        }

        getHouseColor = () => {
            return this.houseColor
        }

        getTenants = () => {
            return this.tenants
        }
    }

let house = new House('12 jude avenue London', 22, 'Blue', [person1, person2, person3] )

console.log(house.getTenants())

The output of the above code snippet will be

[
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],      
    name: 'Layobright',
    age: 25,
    education: 'Tertiary',
    gender: 'Male'
  },
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],      
    name: 'Juliet',
    age: 23,
    education: 'Tertiary',
    gender: 'Female'*
  },
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],      
    name: 'Johnson',
    age: 27,
    education: 'Secondary',
    gender: 'Male'
  }
]

As you can see the output is actually three different person objects each containing tenants information.

Now let's imagine another person is interested in renting a vacant apartment in my house and I want to add the person to my house class. how do we go about that? stay calm, I will walk you through the process.

The first thing we need to do is to create addTenant method in the house class, so we have to pass an argument of the tenant to the addTenant method just like in the snippet below.

    addTenant = (tenant) => {

    }

Don't forget that we already have access to the tenants list using this keyword, so all we have to do is push each new tenant inside the tenants array using the javascript push method

    addTenant = (tenant) => {
        return this.tenants.push(tenant)
    }

Now let's add theaddTenant method inside the House class

     class House{
        constructor(address, houseNumber, houseColor, tenants){
            this.address = address
            this.houseNumber = houseNumber
            this.houseColor = houseColor
            this.tenants = tenants
        }

        getAddress = () => {
            return this.address
        }

        getHouseNumber = () => {
            return this.houseNumber
        }

        getHouseColor = () => {
            return this.houseColor
        }

        getTenants = () => {
            return this.tenants
        }

        addTenant = (tenant) => {
            return this.tenants.push(tenant)
        }
    }

Having added the addTenant method inside the House class, let's add the new tenant information to the list of tenants

    let person4 =  new Person('John', 12, 'Primary', 'Male')

so we pass the new created tenant as an argument to the addTenant method inside the house class.

    house.addTenant(person4)

After adding the new tenant, we need to get all tenants to see if the new tenant has been added to the list.

Run the below snippet to get the new list of all tenants

    console.log(house.getTenants() )

The output for the above snippet will be

[
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],
    name: 'Layobright',
    age: 25,
    education: 'Tertiary',
    gender: 'Male'
  },
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],
    name: 'Juliet',
    age: 23,
    education: 'Tertiary',
    gender: 'Female'
  },
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],
    name: 'Johnson',
    age: 27,
    education: 'Secondary',
    gender: 'Male'
  },
  Person {
    getName: [Function: getName],
    getAge: [Function: getAge],
    getEducation: [Function: getEducation],
    getGender: [Function: getGender],
    name: 'John',
    age: 12,
    education: 'Primary',
    gender: 'Male'
  }
]

If you check the output in your console, you will see that we have a new tenant object which is added to the tenants array, so this way we are able to actually change the data, mutate the data inside of our objects which is exactly what OOP entails.

Conclusion

Now I just introduced you to the basics of object-oriented programming so in the next chapter of this article which is part two, I will be talking about understanding the four pillars of OOP as a beginner and I will demonstrate how they are applied in Javascript.

That's all!. If you find this post helpful please like and share. You can find more about me on linkedIn., Github.