What is a Constructor?
A constructor is a special method in a class that automatically runs when you create an object.
Think of it like this:
🧱 When you build a LEGO house (object), a constructor is like the instruction manual that tells how the pieces should be placed right from the start.
🧃 Why Do We Use Constructors?
Instead of writing code to manually set values every time we create an object, we let the constructor do it for us automatically.
🧪 Without Constructor Example
class Student {
String name;
int age;
}
public class Main {
public static void main(String[] args) {
Student s = new Student(); // create object
// manually set values
s.name = "Sanvi";
s.age = 20;
System.out.println(s.name + " is " + s.age + " years old.");
}
}
Output:
Sanvi is 20 years old.
✅ With Constructor Example
class Student {
String name;
int age;
// 👇 This is the constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Jatasya", 22); // set values during object creation
System.out.println(s.name + " is " + s.age + " years old.");
}
}
Output:
Jatasya is 22 years old.
📌 Key Points About Constructors
Feature | What It Means |
---|---|
Same name as class | The constructor must have the same name as the class |
No return type | Constructors do not return anything (not even void) |
Runs automatically | It runs as soon as the object is created |
Can have parameters | You can pass values into the constructor, just like methods |
🧰 Types of Constructors
- Default Constructor (no parameters)
- Parameterized Constructor (takes values when creating object)
🧪 Default Constructor Example
class Animal {
Animal() {
System.out.println("An animal is created.");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Animal(); // no values passed
}
}
Output:
An animal is created.
🧪 Parameterized Constructor Example
class Animal {
String type;
Animal(String t) {
type = t;
}
void show() {
System.out.println("This is a " + type);
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Animal("Dog");
dog.show();
}
}
Output:
This is a Dog
🤔 When Should You Use a Constructor?
- When you want to automatically set values when an object is created.
- When you want every object to have some initial setup.
🎯 Simple Analogy
🍼 Constructor is like a baby delivery checklist:
When a baby (object) is born (created), it automatically gets:
- Name tag
- ID
- Baby clothes
You don’t manually do this every time — the constructor handles it!
✅ Summary
- A constructor is a special method that runs when you create an object.
- It sets up the object with initial values.
- It makes code cleaner and faster.
- Java will give you a default constructor if you don’t write one.
- You can also make your own constructor with parameters.
0 Comments
If you have any doubts, Please let me know