🔹 Classes and Objects
**Classes and Objects** are the fundamental building blocks of **Object-Oriented Programming (OOP)**. A **class** is a blueprint for creating objects, while an **object** is an instance of a class.
📌 Why Use Classes and Objects?
Classes and objects allow us to **structure code efficiently** and promote **code reusability and modularity**.
- ✅ **Encapsulation** – Groups data and behavior together.
- ✅ **Code Reusability** – Once a class is created, it can be used multiple times.
- ✅ **Modularity** – Breaks a complex system into smaller, manageable parts.
- ✅ **Inheritance & Polymorphism** – Helps in extending and modifying behavior easily.
💡 Real-Life Example
Consider a **Car**. A class `Car` defines attributes like `brand`, `color`, `speed`, and behaviors like `drive()` and `brake()`. Each individual car (e.g., a red Tesla) is an object of the `Car` class.
🖥️ Classes and Objects in Java
Example of a simple **Java class and object**:
class Car {
String brand;
int speed;
Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Tesla", 120);
myCar.drive();
}
}
🖥️ Classes and Objects in Python
Example of a simple **Python class and object**:
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def drive(self):
print(f"{self.brand} is driving at {self.speed} km/h")
my_car = Car("Tesla", 120)
my_car.drive()
🎯 Summary
**Classes and Objects** are the foundation of **OOP**. They help in organizing code efficiently, enabling **reusability, encapsulation, and modularity**. Using classes, we can create multiple objects with the same properties and methods, making development more structured and scalable.