JavaScript By Using OOPS Concept?

Introduction

        In this tutorial, we will explore the fundamentals for Object Oriented Programming(OOPS) in JavaScript in a Practical way with examples

Types of Contents

  • first-class
  • first instance
  • inheritance
  • encapsulation
  • polymorphism
  • abstract classes

First Class

In this section we are creating our first class. Remember to add the constructor method that will enable the creation of instances(objects) based on our class


class Animals {
    name;
    age ;
    constructor(Name, Age) {
        this.name = Name;
        this.age = Age;
    }
    getInfo(){
        return(`The name of the animal is${this.name} and age is ${this.age}`)
    }
}

First Instances

On the Previous Section we created a new class, added a constructor method that takes in 2 arguments- name and age. To create an object from this constructor method we need to use the new keyword and pass in the given name and age of the animal object that we are creating. We also have added a getInfo method that returns the information about the object

const FirstAnimal = new Animals('Rex',2);
console.log(FirstAnimal);
console.log(FirstAnimal.getInfo());
const SecondAnimal = new Animals('Deer',3);
console.log(SecondAnimal);
console.log(SecondAnimal.getInfo());

>Animal {name:'Rex',age:2}
The name of the animal is Rex and age is 2
>Animal {name:'Deer',age:3}
The name of the animal is Deer and age is 3

Inheritance

Class inheritance is a feature that enables certain classes to take all the methods and properties of another one (parent class) and makes it possible to extend the parent class by adding more

class Dog extends Animals{
    constructor(name,age,bread){
        super(name,age)
        this.bread = bread
    }
    bark(){
        return 'woof'
    }
}

class Cat extends Animals{
    constructor(name,age,weight){
        super(name,age)
        this.weight = weight
    }
}

const myDog = new Dog('Rex',2,'German Shepard')
console.log(myDog.getInfo())
console.log(myDog.bread)
console.log(myDog.bark())

const myCat = new Cat('Whiskers',5,'5kg')
console.log(myCat.getInfo())
console.log(myCat.weight)

The name of the animal is Rex and age is 2
German Shepard
woof
The name of the animal is Whiskers and age is 5
5kg


Encapsulation

Encapsulation is a restriction mechanism making accessing the data impossible without using special methods dedicated for this. In the example below we marked weight as a private property and in order to get and set a value we need to use the greater and setter method


class Cat extends Animals{
    #weight  ///Mark as Private
    constructor(name,age,weight){
        super(name,age)
        this.#weight = weight
    }
    getWeight(){ /// getter
        return this.#weight
    }
    setWeight(weight){ ///setter
        this.#weight = weight
    }
}


const myCat = new Cat('Whiskers',5,'5kg')
console.log(myCat.getWeight())
myCat.setWeight('6kg')
console.log(myCat.getInfo())

Output
5kg
6kg


Polymorphism

Polymorphism is a concept that utilizes inheritance for reusing methods multiple times with a different behaviour depending on class types. To Understand this lets look at our example - in the dog class we will remove the bark method and  in animal class we will add a makeSound method which will be overhidden by cat and dog classes


class Animals {
    constructor(Name, Age) {
        this.name = Name;
        this.age = Age;
    }
    makeSound(){
        return(`some nice sound made`)
    }
}
class Dog extends Animals{
    constructor(name,age,bread){
        super(name,age)
        this.bread = bread
    }
    makeSound(){
        return 'woof'
    }
}

class Cat extends Animals{
    constructor(name,age,weight){
        super(name,age)
        this.weight = weight
    }
    makeSound(){
        return 'meow'
    }
}

const myDog = new Dog('Rex',2,'German Shepard')
const myCat = new Cat('Whiskers',5,'5kg')

console.log(myDog.makeSound())
console.log(myCat.makeSound())


Output

woof
meow



Abstract class

Abstract class is a class which can't be instantiated and requires subclasses which inherit from a particular abstract class to provide implementations. We will change the Animal class to an abtract class. It will not be possible to create a instance of this class anymore like on side number 3 and we will mark  makeSound as an abstract method - in order to use it, a subclass must declare its own implementation of this method



class Animals {
    constructor(Name, Age) {
        this.name = Name;
        this.age = Age;
        if(this.contructor == Animals){
            throw new Error("Can't create a instances of Abtract class");
        }
    }
    makeSound(){
        throw new Error("abtract method doesn't have an implementation");
    }
}

class Dog extends Animals{
    constructor(name,age,bread){
        super(name,age)
        this.bread = bread
    }
    makeSound(){
        return 'woof'
    }
}

class Cat extends Animals{
    constructor(name,age,weight){
        super(name,age)
        this.weight = weight
    }
    // makeSound(){
    //     return 'meow'
    // }
}

// const myAnimal = new Animals('Barney',2); /* Can't instantiate anymore*/
const myDog = new Dog('Rex',2,'German Shepard')
const myCat = new Cat('Whiskers',5,'5kg')

console.log(myCat.makeSound()) /* this will give us an error since makeSound() method isn't available */