Constructor

🛠️ What is a Constructor in Java?

A constructor is a special block of code that:

  • Has the same name as the class
  • No return type (not even void)
  • Gets called automatically when you create an object using new
class Student {
    Student() {
        System.out.println("Object created!");
    }
}

❓ Why Constructor?

✅ To initialize objects:

When you create a new object, Java needs a way to assign initial values — that’s where constructors come in.

✅ Without constructor:

Student s = new Student();
s.name = "Vignesh";  // Manual setup

✅ With constructor:

Student s = new Student("Vignesh"); // Clean and quick

🕒 When to Use Constructor?

Use Case Use Constructor?
Initializing values ✅ Yes
Creating multiple objects with different data ✅ Yes
Want to set default setup for every object ✅ Yes
No initialization needed ❌ Can skip constructor

🚫 Why NOT to Use Constructor?

  • If your class only has static methods (like utility classes)
  • If you're using setters() or factory methods
  • If you want to use frameworks (like Spring), where object creation is automatic

📍 Where to Use Constructor?

  • In model classes (User, Product, Book)
  • In real-time apps like login system, e-commerce, etc.
  • In OOP-based programs

⚡ Why ONLY Non-Static Constructors in Java?

👉 Because constructors are meant to create objects.

🤔 Static = belongs to class

But constructor = used to create instances (objects)

So it makes no sense to make constructors static.

You need an object to call non-static methods — constructor is the very step that creates that object!


🧪 Why NO Return Type in Constructor?

Because:

  • Java knows automatically it has to return the object of that class.
  • If you add a return type, Java will treat it as a normal method, NOT a constructor.

🔥 Example:

public class Demo {
    Demo() { }         // ✅ Constructor
    void Demo() { }     // ❌ This is a method (not a constructor!)
}

🧠 Summary (Quick Table):

Feature Why
Non-static Because constructors create objects, and static doesn’t need objects
No return type Java returns object implicitly. Return type would make it a normal method
Same name as class So Java knows this is a constructor
Used when You want to initialize object values
Not used when You’re only using static methods, or initialization isn’t required