In OOPs (Object-Oriented Programming System), a constructor is a special method that is automatically called when an object of a class is created.
👉 It is mainly used to initialize objects (assign values to variables when the object is created).
Key Points about Constructor:
Name same as class → A constructor must have the same name as the class.
No return type → Not even void.
Called automatically → Executes when an object is created using new.
Used for initialization → Sets initial values for object variables.
Program
class Student {
int age;
String name;
// Constructor
Student(int a, String n) {
age = a;
name = n;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
// Object creation calls constructor
Student s1 = new Student(20, "Arun");
Student s2 = new Student(22, "Kumar");
s1.display();
s2.display();
}
}
Output
Name: Arun, Age: 20
Name: Kumar, Age: 22
Why we need constructors in OOPs?
- Automatic Initialization
When you create an object, its variables get values immediately without calling any extra method.
Student s = new Student(20, "Arun"); // values set automatically
- Code Simplicity
Without constructors, you would write a method like setData() and call it manually after creating the object.
Constructors remove this extra step.
- Encapsulation Support
They help keep variables private and still allow controlled initialization.
- Different Ways of Object Creation
With overloaded constructors (same name, different parameters), we can create objects in different ways.
Student s1 = new Student(); // default constructor
Student s2 = new Student(20, "Arun"); // parameterized constructor
- Readability & Maintainability Code becomes more organized because initialization is tied to object creation.
Example without constructor
class Student {
int age;
String name;
void setData(int a, String n) {
age = a;
name = n;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.setData(20, "Arun"); // must call method separately
}
}
Example With Constructor
class Student {
int age;
String name;
Student(int a, String n) {
age = a;
name = n;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(20, "Arun"); // initialized automatically
}
}
Top comments (0)