SmartCodingTips

🧱 Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that helps organize and structure code by modeling real-world entities as objects. JavaScript supports OOP through prototypes and ES6 class syntax.

🎯 Why Use OOP?

  • Encapsulation – Keep data and behavior in one place
  • Reusability – Create reusable code with classes
  • Inheritance – Share behavior across related objects
  • Abstraction – Hide complexity from the outside

📦 Creating a Class

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

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}

const user = new Person("Alice", 25);
user.greet();

🧬 Inheritance

class Student extends Person {
  constructor(name, age, subject) {
    super(name, age); // Call parent constructor
    this.subject = subject;
  }

  study() {
    console.log(`${this.name} is studying ${this.subject}`);
  }
}

const s1 = new Student("Bob", 20, "Math");
s1.greet();
s1.study();

⚙️ Object Literals vs Classes

// Object literal (simple use-case)
const user = {
  name: "Charlie",
  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
};

🧠 Key Concepts Recap

  • Class – Template for creating objects
  • Object – Instance of a class
  • Constructor – Method that initializes the object
  • Inheritance – Ability of one class to extend another
  • Method – Function inside a class
💡 Tip: Use classes when building large-scale apps or when multiple objects share similar structure or behavior.