# Classes and Objects

> A class is the blueprint; objects are the live instances — each with its own state, all sharing the same behavior.

- **Category**: Oop Concepts
- **Subcategory**: fundamentals
- **Canonical URL**: https://designpattern.fyi/patterns/classes-objects/

---

## Description
**Intent**: Model real-world entities with both data and behavior in a single reusable unit that can be instantiated many times.

**Context**: You need multiple things of the same shape — multiple users, products, connections — each holding its own state but all sharing the same methods. Without classes, you're copying structures by hand and keeping them in sync.

**Solution**: Define a class with properties (state) and methods (behavior). Instantiate with new — each instance gets its own copy of the state; methods are shared from the class definition. The class is the template; the object is the runtime reality.



## Use Cases
Modeling anything with both state and behavior. Creating multiple instances of the same structure. Grouping related data and the operations on it into a single, cohesive unit.



## Implementation Example

```javascript
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  greet() {
    return `Hello, ${this.name}!`;
  }
}

const user1 = new User('Alice', 'alice@example.com');
const user2 = new User('Bob', 'bob@example.com');

console.log(user1.greet()); // "Hello, Alice!"
console.log(user2.greet()); // "Hello, Bob!"
```



## Trade-offs


### Advantages

- Reusable blueprints — define once, instantiate as many times as needed

- Encapsulates data and behavior together in one place

- Clear, self-documenting structure for entities and domain concepts




### Considerations & Drawbacks

- Overkill for simple data shapes where a plain object or struct would do

- Requires understanding of the instantiation model — new, constructor, prototype chain







