🔹 Constructor in Java
When you create an object in Java, you often want it to start with some initial values. That’s where a constructor comes in!
Think of it like the entry gate of a house – whenever you enter (create an object), it decides how things will look inside.
✨ What is a Constructor?
A constructor in Java is a special method that:
-
Has the same name as the class.
-
Does not have a return type (not even
void). -
Is automatically called when an object is created.
👉 In short: It initializes objects!
🛠 Types of Constructors in Java
1️⃣ Default Constructor
-
Provided by Java automatically if you don’t create any constructor.
-
Initializes object with default values (0, null, false, etc.).
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Constructor called automatically
System.out.println(s1.name + " - " + s1.age);
}
}
2️⃣ Parameterized Constructor
-
Used when you want to initialize objects with specific values.
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Amit", 21);
Student s2 = new Student("Riya", 22);
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
3️⃣ Constructor Overloading
-
You can define multiple constructors in a class with different parameters.
-
Java will decide which one to call based on arguments.
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Not Assigned";
age = 0;
}
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(); // Calls default
Student s2 = new Student("Rahul", 20); // Calls parameterized
System.out.println(s1.name + " - " + s1.age);
System.out.println(s2.name + " - " + s2.age);
}
}
🚀 Why are Constructors Important?
✅ Save time by initializing objects automatically.
✅ Increase code readability.
✅ Essential for object-oriented programming (OOP).
📌 Quick Recap
-
Constructors initialize objects.
-
Same name as the class, no return type.
-
Types: Default, Parameterized, Overloaded.
💡 Pro Tip for Students: Constructors are one of the most asked concepts in Java exams & interviews. Practice writing small classes with multiple constructors to master them!