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 |
Top comments (0)