DEV Community

Murali Rajendran
Murali Rajendran

Posted on

What is a Constructor?

A constructor is like a “welcome setup” that runs automatically when an object is created.
Think of it like a welcome gift pack 🛍️ — whenever you create a new object, Java runs the constructor to set up initial values.
🔹 Syntax:
class ClassName {
ClassName() {
// setup code (like a welcome gift)
}
}

🧩 3 Types of Constructors:

Type Example Description

Default constructor SuperMarket() {}
Created automatically by Java if you don’t make one yourself. It sets default values (0, null, false).
No-parameter constructor

SuperMarket() { groceryProductPrice = 50; }
You create it manually. It has no parameters but assigns custom default values.
Parameterized constructor

SuperMarket(int groceryProductPrice, int choc) { ... }
You pass values while creating an object.

🧠 2. this Keyword — “I belong to this object”
👉 Think of this as “me” inside the class.
When a local variable name is same as an instance variable name, this helps Java understand which one belongs to the object.

Top comments (0)