DEV Community

Vigneshwaralingam
Vigneshwaralingam

Posted on

πŸš€ Java Programming – Day 10: Constructor?

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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

❓ 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
Enter fullscreen mode Exit fullscreen mode

βœ… With constructor:

Student s = new Student("Vignesh"); // Clean and quick
Enter fullscreen mode Exit fullscreen mode

πŸ•’ 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!)
}
Enter fullscreen mode Exit fullscreen mode

🧠 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

Top comments (0)