DEV Community

loading...
Cover image for Understanding the Object-Oriented Programming

Understanding the Object-Oriented Programming

rohanshakya profile image Rohan_Shakya ・6 min read

Object-Oriented Programming is a design philosophy also known as OOP. Object-Oriented Programming(OOP) uses different sets of programming languages than old procedural programming languages(C, Pascal, etc.)Everything in OOP is grouped as self-sustainable “objects”. Hence you gain reusability by means of OOP concepts.

OOP allows the decomposition of a problem into a number of entities called objects and then builds data and functions around these objects. Data cannot be accessed directly, they are only accessible through the member function. There might be a number of objects in a program written in OOP language. Those objects can communicate with each other by calling their respective member functions. Organization of data and function in OOP is shown below:

Alt Text

OOP has taken the best ideas of structured programming and combined them with several powerful new concepts that encourage us to perform the task of programming in a new way. In general, when programming in an object-oriented fashion, we break down a problem into a subgroup of related parts that take into account both code and data related to each group.

The terminology used in OOP:

Object

An object is any entity, thing, or organization that exists in the real world, It consists of two fundamentals characteristics: its attributes and behaviors. For example, a dog is an object having attributes such as color, weight, age, etc, and behaviors such as barking. In OOP, attributes are represented by data(variables) and the behaviors are represented by the functions.

Object Car
Data                              Function
plateNumber = 120                 accelerate()
speed = 100                       
color = black
Enter fullscreen mode Exit fullscreen mode
// Object in Javascript

// Defining object 

// Using an Object Literal
var car = {
  plateNumber: 120,
  maxSpeed: 100,
  color: 'black',
  accelerate: function(speed, time){
    console.log(speed * time);
  }
}

// Using an Object Constructor
var Car = function(plateNumber, maxSpeed, color){
  this.plateNumber = plateNumber;
  this.maxSpeed = maxSpeed;
  this.color = color;
  this.accelerate = function(speed, time){
    console.log(speed * time);
  }
}
var car1 = new Car(120, 100, 'black');
Enter fullscreen mode Exit fullscreen mode

Objects are the basic run-time entities in an object-oriented system that may be created or destroyed at run time. The data and function containing in an object are called its member data and member function. The member function of an object can only access its data. The concept behind OOP is to integrate both data and function into a single entity. This entity is also called an object.

Class

A class is simply a representation of a type of object. It is the blueprint/prototype that describes the details of an object. The entire set of data and code of an object can be made a user-defined data type with the help of a class. Once a class has been defined, we can create any number of objects associated with that class. For example, mango, apple, and orange are members of class fruit. If the fruit has been defined as a class, then the statement fruit mango will create an object mango belonging to the class fruit.

A class has three areas: public, private, and protected. The functions and variables defined inside the public areas can be accessed by any object. The functions and variables defined inside the private areas can be accessed by the object of the same class and the protected areas can be accessed by the object from the same class and derived class. It incorporated the concept of data hiding.

Class Student                     Class Vehicle
Id                                Name
Name                              Maker
getName()                         Engine
printGrade()                      getDetails()
Enter fullscreen mode Exit fullscreen mode
// Defining Class in Javascript using es6

class Vehicle { 
  constructor(name, maker, engine) { 
    this.name = name; 
    this.maker =  maker; 
    this.engine = engine; 
  } 
  getDetails(){ 
      return (`The name of the bike is ${this.name}.`) 
  } 
} 
// Making object with the help of the constructor 
let bike1 = new Vehicle('Hayabusa', 'Suzuki', '1340cc'); 
let bike2 = new Vehicle('Ninja', 'Kawasaki', '998cc'); 
Enter fullscreen mode Exit fullscreen mode

Defining class doesn't create an object but class is the description of the object’s attributes and behavior. So no memory is allocated when a class is created.

Data Abstraction & Encapsulation

In OOP, abstraction defines the conceptual boundaries of an object. Abstraction is the act of representing essential features without including the background details. It focuses on the outside view of an object, separating its essential behavior from its implementation. To understand this concept, take an example of ‘switch-board’. We only press particular switched as per our requirement. We need not know the internal working of these switched. This is an abstraction where we only know the essential things to operate on a switch-board without knowing the background details of the switch-board.

Encapsulation is a way of organizing data and function into a structure (called class) by concealing (hiding) the way the object is implemented, which is preventing access to data by any means other than those specified. Encapsulation, therefore, guarantees the integrity of the data contained in the object. The best application of encapsulation is making the data fields private and using public access to functions. However, we cannot hide an entire object. To use an object, a part of it needs to be accessed by users. To provide this access, abstraction is used. Abstraction provides access to a specific part of data while encapsulation hides the data. Therefore, abstraction and encapsulation complement each other.

//encapsulation example 
class person{ 
    constructor(name,id){ 
        this.name = name; 
        this.id = id; 
    } 
    addAddress(addr){ 
        this.addr = addr; 
    } 
    getDetails(){ 
        console.log(`Name is ${this.name},Address is: ${this.addr}`); 
    } 
} 

let person1 = new person('John',20); 
person1.addAddress('California'); 
person1.getDetails(); 
Enter fullscreen mode Exit fullscreen mode
// Abstraction example 

function person(fname,lname){ 
    let firstname = fname; 
    let lastname = lname; 

    let getDetails_noaccess = function(){ 
        return (`First name is: ${firstname} Last  
            name is: ${lastname}`); 
    } 

    this.getDetails_access = function(){ 
        return (`First name is: ${firstname}, Last  
            name is: ${lastname}`); 
    } 
} 
let person1 = new person('John','Smith'); 
console.log(person1.firstname); 
console.log(person1.getDetails_noaccess); 
console.log(person1.getDetails_access()); 
Enter fullscreen mode Exit fullscreen mode

Inheritance

The process of creating a new class from an existing class in which objects of the new class inherit the attributes and behaviors of the existing class is known as inheritance. The newly created class is called the derived class or child class or subclass and the class from which the new class is created is class base class or parent class or super-class.

The relationships of classes through inheritance give rise to a hierarchy. It permits the expansion and reuse of existing code without rewriting it hence, the concept of inheritance supports the concept of reusability.

Types

  • Single Inheritance: The process of creating a new class from an existing class is a single inheritance that is there is only one base class and only derived class in single inheritance.

Alt Text

  • Multiple Inheritance: The process in which one class can have more than one superclass and inherit features from all parent classes is multiple inheritances.

Alt Text

  • Hierarchical Inheritance: The process of creating several classes from only one class is called hierarchical inheritance that is there are two or more derived classes and only one base class in hierarchical inheritance.

Alt Text

  • Multilevel Inheritance: The process of creating a new class from another derived class is called multi-level inheritance.

Alt Text

  • Hybrid Inheritance: It is the combination of two or more types of inheritance.
//Inhertiance example 

class person{ 
    constructor(name){ 
        this.name = name; 
    } 

    //method to return the string 
    toString(){ 
        return (`Name of person: ${this.name}`); 
    } 
} 

class student extends person{ 
    constructor(name,id){ 
        //super keyword to for calling above class constructor 
        super(name); 
        this.id = id; 
    } 
    toString(){ 
        return (`${super.toString()},Student ID: ${this.id}`); 
    } 
} 
let student1 = new student('John',20); 
Enter fullscreen mode Exit fullscreen mode

Polymorphism

Polymorphism is a generic term that means ‘many forms’. It simply means ‘one name many forms’. More precisely Polymorphism means the ability to request that the same operations be performed by a wide range of different types of things.

Polymorphism is an important feature of OOP which refers to the ability of an object to take on different forms depending upon situations. It simplifies coding and reduces the rework involved in modifying and developing an application. It is extensively used in implementing inheritance.

Alt Text

Operator overloading and function overloading are examples of polymorphism in OOP.

Conclusion

The concept of an object helps to translate our thoughts into a program. It provides a way of solving a problem in the same way as a human being perceives a real-world problem and finds out the solution. It is possible to construct large reusable components using object-oriented techniques.

Thanks for your time!! Hope you like it 😃😃

Discussion (3)

Collapse
lukeshiru profile image
LUKE知る

JavaScript is way better suited for FP, but it certainly is a multi-paradigm language. So if you come from OOP languages, it still feels "natural". Either way, I always tell folks coming to JS from OOP languages to take a look to the FP paradigm instead of keep doing the same stuff they were already doing. This is mainly because I did the transition from OOP to FP a few years back and I never looked back 🤣

Collapse
havespacesuit profile image
Eric Sundquist

I've been reading Clean Code by Robert Martin and trying to wrestle with some of this. He suggests limiting your function arguments to as few as possible (3 being about the most he will tolerate), and letting a lot of the other variables live in class instance properties.

It makes a lot of sense for OOP, but the FP project I work on has sometimes huge argument lists, as we are trying to prevent global scope and limit what the function itself is responsible for.

Something I'm still trying to work out how to fix... OOP is definitely tempting me, though it would be a herculean task to convert parts of our code base at this point.

Collapse
lukeshiru profile image
LUKE知る • Edited

Ideally when working with FP you should try to limit the amount of arguments to 1, and use currying when you need more, this way the reuse is incremented greatly. For example instead of having:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const doubles1 = arr1.map(value => value * 2);
const doubles2 = arr1.map(value => value * 2);
Enter fullscreen mode Exit fullscreen mode

You could have:

const times => value1 => value2 => value1 * value2;
const map => mapper => source => source.map(mapper);

const double = times(2);
const mapDouble = map(double);

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const doubles1 = mapDouble(arr1);
const doubles2 = mapDouble(arr2);
Enter fullscreen mode Exit fullscreen mode

This way, if you need to have the triple, you can add a new triple function which only does times(3), if you need to map the triples you can just map(triple), and so on. Best of it is that you just need to actually test the base functions (map & times), because everything is just reusing those.

When you design function as transformers of input instead of runners of sequences of instructions, everything becomes easier to maintain, reuse and test.

Forem Open with the Forem app