# 4 principles of OOP

#### Encapsulation:

We wrap code into boxes related to one another. This box can interact with each other using the methods and properties that we make it available.

This makes the code easier to maintain and reusable.

```javascript
Ex:
const person = {
    firstName: 'Vijay',
    lastName: 'Deepak',
    getName() {
        return `${this.firstName} ${this.lastName}`;
    }
};
```

#### Abstraction:

Hiding the complexity from the user.

```javascript
Ex:
function complexFn(data) {
    // complex code & bussiness logics
}

complexFn("hi"); // code of the function is not considered
```

#### Inheritance:

Avoid code rewrite and save memory spaces with shared methods.

```javascript
Ex:
class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    getFullName() {
        return `${this.firstName} ${lastName}`;
    }
}

class Men extends Person {
    constructor(firstName, lastName) {
        super(firstName, lastName);
    }
}

const vijay = new Men('Vijay', 'Deepak');
vijay.getFullName(); // Vijay Deepak

```

#### Polymorphism: ( Many Forms )

An ability to call a same method in different object, in each object responding different way. This is also known for Method overriding and Method Overloading.

**Method overriding** is the ability of the inherited class rewriting the virtual method of the base class.

**Overloading** a method (or function) is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters).

```javascript
Ex:
class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
    
    getFullName() {
        return `${this.firstName} ${lastName}`;
    }
}

class Men extends Person {
    constructor(firstName, lastName) {
        super(firstName, lastName);
    }
    
    getFullName() {
        return `Sorry I can't`;
    }
}

const vijay = new Men('Vijay', 'Deepak');
vijay.getFullName(); // Sorry I can't
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://javascript-1.gitbook.io/javascript/oop/4-principles-of-oop.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
