Learn OOPS concepts Encapsulation, Inheritance and Polymorphism using very simple and easy to understand code examples that can run on a node.js

Dear QA and Automation Engineers!

In this article we will learn OOPs concepts. We will understand what is Object Oriented Programming Paradigm and we will build our foundation in OOPS concepts. We will use React.js framework to run our examples by creating web pages. We will also run an API server and learn promises and async features of JavaScript.

In this tutorial article we will learn following

  1. Basic Class Creation (Defining a Class)
  2. Creating Objects from a Class
  3. Encapsulation (Using Private Properties)
  4. Creating Subclasses (Extending Classes)
  5. Inheritance (Parent & Child Relationship)
  6. Polymorphism (Overriding Methods Differently)

Please complete step 1, 2, 3 and 4 before proceeding to Step 5:

Step 1: Set up node.js webserver and mocha test framework env

https://www.dhirubhai.net/pulse/ui-automation-testing-using-nodejs-webserver-reactjs-mohammed-e4eje/

Step 2: Create a home page, login page, secure dashboard and shopping cart module: https://www.dhirubhai.net/pulse/creating-login-shopping-cart-module-qas-using-nodejs-server-mohammed-z1vhc/

Step 3: Create four Mocha UI test scripts to test your own website

https://www.dhirubhai.net/pulse/create-update-mocha-test-scripts-webdriverio-your-website-mohammed-6vfnc/

Step 4: Extend Mocha test to test shopping cart and run six test scripts

https://www.dhirubhai.net/pulse/extend-your-own-nodejs-website-testing-test-shopping-cart-mohammed-slbmc/

Learn OOPS concepts using JavaScript and practise them using React.js

Before we proceed, we will need to update our website and preserve our Shopping Cart website so that we can switch between OOPS concepts and website as and when needed.

Stop your webserver running from "\reactjsserver\my-app\" location (If it is running then do this step):

cntrl-c        

Please copy your "src" folder located at "\reactjsserver\my-app" location with a new name "src-mywebsite"

xcopy src src-mywebsite /E /I /Y        

Now we can make change in this "src" folder. This saves us from creating another react.js app, which downloads lots of modules and takes time.

Whenever we want to run our shoppingcart website, we can rename this "src" folder to "src-oops-learning" and then rename "src-mywebsite" back to "src" folder and relaunch the website running "npm start" command.

Navigate to your "src" folder, this is where we will edit and create all our OOPS related .js files

cd src        

Basic Class Creation (Defining a Class)

Let us learn how to create a base class. We will have data (brand, model, year) and also write a method to return this data back to caller. This concept is popularily called and is part of GETTER and SETTER methods.

basicClass.js - Create this new file

class Vehicle {
    constructor(brand, model, year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
    }

    getDetails() {
        return `${this.year} ${this.brand} ${this.model}`;
    }
}

// Exporting the class so we can use it in React.js later
export default Vehicle;        

What You Learned Here?

  1. How to create objects from a class
  2. How to call methods on objects

Now let us use our base class Vehicles and create Objects using it

Creating Objects from a Class

Update exisiting App.js

import React from "react";
import Vehicle from "./basicClass";

function App() {
    // Creating objects from Vehicle class
    const car1 = new Vehicle("Toyota", "Corolla", 2022);
    const car2 = new Vehicle("Honda", "Civic", 2023);

    return (
        <div>
            <h1>OOP in JavaScript: Vehicles Example</h1>
            <h2>Step 2: Creating Objects</h2>
            <p>{car1.getDetails()}</p>
            <p>{car2.getDetails()}</p>
        </div>
    );
}

export default App;        

Run the code:

set PORT = 5000 && npm start        

What You Learned Here?

  1. How to create objects from a class
  2. How to call methods on objects


Now we will learn Encapsulation (Using Private Properties)

Encapsulation is like medical capsules where medicine is hidden inside a capsule, same way we will hide our data (medicine and core of our program asset) inside a class. When we have data and methods like GETTER and SETTER to operate on data and return or set data, we term it as Encapsulation.

We hide the speed property using JavaScript Encapsulation. What this mean is that we can not directly access "Speed" property by directly calling the variable from outside this class. We have controlled access to the "speed" property and expose our own methods to access it or modify it.

encapsulation.js - - Create this new file

class Vehicle {
    constructor(brand, model, year) {
        this.brand = brand;
        this.model = model;
        this.year = year;
        let speed = 0; // Private variable (cannot be accessed outside)

        this.getSpeed = function () {
            return speed;
        };

        this.accelerate = function (amount) {
            speed += amount;
            return `Speed increased to ${speed} km/h`;
        };
    }

    getDetails() {
        return `${this.year} ${this.brand} ${this.model}`;
    }
}

export default Vehicle;
        

Update exisiting App.js:

import React from "react";
import Vehicle from "./encapsulation";

function App() {
    const car = new Vehicle("Tesla", "Model 3", 2024);

    return (
        <div>
            <h1>OOP in JavaScript: Encapsulation</h1>
            <h2>Step 3: Using Private Properties</h2>
            <p>Initial Speed: {car.getSpeed()} km/h</p>
            <p>{car.accelerate(20)}</p>
        </div>
    );
}

export default App;        

Run the code:

set PORT = 5000 && npm start        

What You Learned Here?

  1. How to hide properties (speed) from direct access
  2. How to use getter methods to access private data


Next we will learn how to create Subclasses (Extending Classes)

Now, we introduce Car and Bike as subclasses of Vehicle.

When we use a base class and create a subclass using keyword "extends" we get access to base class data and methods. We do not have ability to modify base class (parent class) methods (due to Encapsulation OOPS cocept), we can add new methods in subclass and use parents class methods to get data and then update it. This update of data stays in sub class and does not update any base class data directly.

To access parent method we use a special keyword/method "super()"

subclasses.js - Create this new file

import Vehicle from "./encapsulation";

class Car extends Vehicle {
    constructor(brand, model, year, doors) {
        super(brand, model, year);
        this.doors = doors;
    }

    getCarDetails() {
        return `${this.getDetails()} with ${this.doors} doors`;
    }
}

class Bike extends Vehicle {
    constructor(brand, model, year, type) {
        super(brand, model, year);
        this.type = type;
    }

    getBikeDetails() {
        return `${this.getDetails()} which is a ${this.type} bike`;
    }
}

export { Car, Bike };        

Update exisiting App.js

import React from "react";
import { Car, Bike } from "./subclasses";

function App() {
    const myCar = new Car("BMW", "X5", 2023, 4);
    const myBike = new Bike("Yamaha", "YZF-R1", 2022, "sport");

    return (
        <div>
            <h1>OOP in JavaScript: Subclasses</h1>
            <h2>Step 4: Creating Subclasses</h2>
            <p>{myCar.getCarDetails()}</p>
            <p>{myBike.getBikeDetails()}</p>
        </div>
    );
}

export default App;        

Run the code:

set PORT = 5000 && npm start        

What You Learned Here?

  1. How to extend a class using extends
  2. How to reuse parent class properties and methods using super()
  3. How to add new properties and methods in subclasses


Next we will learn Inheritance (Parent & Child Relationship)

Inheritance is like inheriting property of parent by child. A child can inherit their parents property as it is. Then they can use their own skills to improve it. Mukesh Ambani, Businessman is a good example to remember inheritance. He INHERITED businesses from his father and then EXTENDED it to increase his wealth and business.

Overriding in OOPS is changing behavior of base class method by overriding it in subclass.

As we can not control or modify base class encapsulation.js class Vehicle's "getDetails()" method from a subclass we can override it by using same method name. This also exhibits SAME METHOD NAME (Poly) and DIFFERENT functionality or FORM (Morphism) - Polymorphism (Many Forms) that we will study after this example.

The Car and Bike classes inherit features from Vehicle. We now demonstrate overriding methods.

inheritance.js - Create this new file

import Vehicle from "./encapsulation";

class Car extends Vehicle {
    constructor(brand, model, year, doors) {
        super(brand, model, year);
        this.doors = doors;
    }

    getDetails() {
        return `${super.getDetails()} (Car with ${this.doors} doors)`;
    }
}

export default Car;        

Update exisiting App.js

import React from "react";
import Car from "./inheritance";

function App() {
    const myCar = new Car("Mercedes", "C-Class", 2022, 4);

    return (
        <div>
            <h1>OOP in JavaScript: Inheritance</h1>
            <h2>Step 5: Demonstrating Inheritance</h2>
            <p>{myCar.getDetails()}</p>
        </div>
    );
}

export default App;        

Run the code:

set PORT = 5000 && npm start        

What You Learned Here?

  1. How to inherit properties and methods from a parent class
  2. How to override parent methods using super.getDetails()



Next we will learn Polymorphism (Overriding Methods Differently)

When we have SAME METHOD NAME (Poly) and different functionality or FORM (Morphism) - We study it as Polymorphism (Many Forms) OOPS concept.

In this example we will use same getDetails() methods in different subclasses and same method will behave differently based on where it is used,

We now override the getDetails() method differently for Car and Bike.

polymorphism.js - Create this new file

import Vehicle from "./encapsulation";

class Car extends Vehicle {
    getDetails() {
        return `This is a car: ${super.getDetails()}`;
    }
}

class Bike extends Vehicle {
    getDetails() {
        return `This is a bike: ${super.getDetails()}`;
    }
}

export { Car, Bike };        

Update existing App.js

import React from "react";
import { Car, Bike } from "./polymorphism";

function App() {
    const myCar = new Car("Audi", "Q7", 2023);
    const myBike = new Bike("Ducati", "Panigale V4", 2022);

    return (
        <div>
            <h1>OOP in JavaScript: Polymorphism</h1>
            <h2>Step 6: Method Overriding</h2>
            <p>{myCar.getDetails()}</p>
            <p>{myBike.getDetails()}</p>
        </div>
    );
}

export default App;        

Run the code:

set PORT = 5000 && npm start        

What You Learned Here?

  1. How child classes override methods differently
  2. How the same method name behaves differently

These steps teaches OOPS in very simple to understand method. Hope your OOPS concept are clear by now and you can use these in your QA Automation scripts.


Step 6: We will will learn a very important concept in JavaScript and QA Automation called Asynchronus Programming Concept that uses Promises or Async/Await methods.

Coming Soon!


This Series:

Step 1: Set up node.js webserver and mocha test framework env

https://www.dhirubhai.net/pulse/ui-automation-testing-using-nodejs-webserver-reactjs-mohammed-e4eje/

Step 2: Create a home page, login page, secure dashboard and shopping cart module: https://www.dhirubhai.net/pulse/creating-login-shopping-cart-module-qas-using-nodejs-server-mohammed-z1vhc/

Step 3: Create four Mocha UI test scripts to test your own website

https://www.dhirubhai.net/pulse/create-update-mocha-test-scripts-webdriverio-your-website-mohammed-6vfnc/

Step 4: Extend Mocha test to test shopping cart and run six test scripts

https://www.dhirubhai.net/pulse/extend-your-own-nodejs-website-testing-test-shopping-cart-mohammed-slbmc/

Step 5: Learn OOPS concepts using JavaScript and Rect.js

https://www.dhirubhai.net/pulse/learn-oops-concepts-encapsulation-inheritance-using-very-mohammed-xg7qc/





要查看或添加评论,请登录

Shahab M.的更多文章

社区洞察

其他会员也浏览了