What is a Constructor?
A constructor is a special method that is automatically called when an object is created.
In simple words:
A constructor helps to initialize values when we create an object.
Why are Constructors Important?
Constructors help us to:
- Initialize object data easily
- Reduce repetitive code
- Make programs clean and readable
- Automatically assign values during object creation
Real-Time Example: Food Ordering App
Think about a food ordering app like Swiggy or Zomato.
When a user places an order, we need to store:
- Item name
- Price
Instead of setting values manually every time, a constructor does it automatically when the order is created.
Constructor in Java
Default Constructor
class Order {
String item;
Order() {
item = "Burger";
}
}
public class Main {
public static void main(String[] args) {
Order o1 = new Order();
System.out.println(o1.item);
}
}
Output:
Burger
Parameterized Constructor
class Order {
String item;
int price;
Order(String i, int p) {
item = i;
price = p;
}
}
public class Main {
public static void main(String[] args) {
Order o1 = new Order("Pizza", 299);
System.out.println(o1.item + " " + o1.price);
}
}
Output:
Pizza 299
Key Points (Java)
- Constructor name must be same as class name
- No return type
- Automatically called when object is created
Constructor in Python
In Python, constructors are defined using __init__ method.
class Order:
def __init__(self, item, price):
self.item = item
self.price = price
o1 = Order("Pizza", 299)
print(o1.item, o1.price)
Output:
Pizza 299
Key Points (Python)
- Constructor is always
__init__ -
selfrefers to the current object - Automatically runs when object is created
Constructor in JavaScript
In JavaScript, constructors are defined inside a class using constructor().
class Order {
constructor(item, price) {
this.item = item;
this.price = price;
}
}
const o1 = new Order("Pizza", 299);
console.log(o1.item, o1.price);
Output:
Pizza 299
Key Points (JavaScript)
- Use
constructor()method - Use
thiskeyword to assign values - Object is created using
new
Types of Constructors
- Default Constructor
- No parameters
- Assigns default values
- Parameterized Constructor
- Takes input values
- Used for dynamic data
Common Mistakes
Forgetting to use new keyword (JavaScript)
Writing wrong constructor name (Java)
Not using this or self
Missing parameters
When Should You Use Constructors?
- When creating objects with initial values
- When working with real-world applications
- When you want clean and reusable code
Real-World Usage
Constructors are used in:
- Food ordering apps
- E-commerce websites
- Banking systems
- Student management systems
Conclusion
Constructors are one of the most important concepts in programming.
They help you:
- Initialize objects easily
- Write cleaner code
- Build real-world applications efficiently
Top comments (0)