🔹 Constructors and Destructors
**Constructors and Destructors** are special methods in Object-Oriented Programming (OOP) that manage object initialization and cleanup. A **constructor** is automatically called when an object is created, while a **destructor** is called when an object is destroyed.
📌 Why Use Constructors and Destructors?
They ensure proper **initialization and cleanup** of objects without requiring manual intervention.
- ✅ **Automatic Execution** – Constructors run automatically upon object creation.
- ✅ **Code Efficiency** – Reduces redundant initialization code.
- ✅ **Prevents Resource Leaks** – Destructors help in releasing resources like memory or file handles.
💡 Real-Life Example
Consider a **Database Connection**. A constructor can **open the connection** when an object is created, and a destructor can **close it** when it's no longer needed.
🖥️ Constructors and Destructors in Java
Java has constructors but does not have explicit destructors; instead, it relies on **Garbage Collection (GC)**.
class Car {
String brand;
// Constructor
Car(String brand) {
this.brand = brand;
System.out.println(brand + " is created.");
}
protected void finalize() {
System.out.println(brand + " is destroyed.");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Tesla");
}
}
🖥️ Constructors and Destructors in Python
Python uses `__init__` as a constructor and `__del__` as a destructor.
class Car:
def __init__(self, brand):
self.brand = brand
print(f"{self.brand} is created.")
def __del__(self):
print(f"{self.brand} is destroyed.")
my_car = Car("Tesla")
🎯 Summary
**Constructors and Destructors** ensure smooth object lifecycle management. While constructors handle **initialization**, destructors handle **cleanup**, making programs more efficient and reducing resource leaks.