• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? Understanding the 4 Main Concepts of Object-Oriented Programming (OOP) with Examples

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Object-Oriented Programming (OOP) is a popular programming paradigm based on the concept of “objects.” It makes code reusable, modular, and easier to maintain. In this blog, we’ll dive into the 4 main pillars of OOP:

? Encapsulation
? Abstraction
? Inheritance
? Polymorphism

We'll explore each with simple JavaScript examples to make them easier to understand.

1️⃣ Encapsulation — Hiding the Complexity
Definition: Encapsulation is the process of wrapping data (variables) and methods (functions) into a single unit (class). It restricts direct access to some of the object’s components.

Example:


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

getDetails() {
return `${this._name} is ${this._age} years old.`;
}

setAge(newAge) {
if (newAge > 0) {
this._age = newAge;
}
}
}

const person = new Person("Afsar", 22);
console.log(person.getDetails()); // Afsar is 22 years old
person.setAge(25);
console.log(person.getDetails()); // Afsar is 25 years old

? Here, the _age and _name are “private” (by convention), and access is controlled using getter/setter.

2️⃣ Abstraction — Focus on What, Not How
Definition: Abstraction hides unnecessary details and shows only the essential features of an object.

Example:


class Car {
startEngine() {
console.log("Starting engine...");
}

drive() {
this.startEngine();
console.log("Driving the car...");
}
}

const car = new Car();
car.drive();

? The user doesn’t need to know how startEngine() works internally — just that calling drive() makes the car move.

3️⃣ Inheritance — Reuse the Code
Definition: Inheritance allows one class to inherit the properties and methods of another class.

Example:


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

speak() {
console.log(`${this.name} makes a sound.`);
}
}

class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}

const dog = new Dog("Tommy");
dog.speak(); // Tommy barks.

4️⃣ Polymorphism — One Interface, Many Forms
Definition: Polymorphism allows objects to be treated as instances of their parent class, but with different behaviors.

Example:


class Shape {
area() {
return 0;
}
}

class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}

area() {
return Math.PI * this.radius ** 2;
}
}

class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}

area() {
return this.width * this.height;
}
}

const shapes = [new Circle(3), new Rectangle(4, 5)];
shapes.forEach(shape => {
console.log(shape.area());
});

? Different shapes respond to the area() method in their own way.

? Conclusion
The 4 pillars of OOP — Encapsulation, Abstraction, Inheritance, and Polymorphism — help us write clean, scalable, and maintainable code.

? Try implementing these concepts in your next project. The more you practice, the more natural OOP will become!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу