Introduction
A Constructor is a special member of a class that is automatically called when an object is created. Its primary purpose is to initialize the object’s data members with default or user-defined values. Constructors play an essential role in Object-Oriented Programming (OOP) because they ensure that every object starts its life in a valid and consistent state.
For example, consider a Student class with fields such as id, name, and course. Instead of assigning values separately after creating each object, a constructor allows you to initialize these values during object creation, making the code cleaner, safer, and easier to maintain.
What is a Constructor?
A Constructor is a special member of a class that is automatically executed when an object is created.
Its primary purpose is to initialize object fields and prepare the object for use.
Definition:
A constructor is a special member of a class that has the same name as the class, does not have a return type, and is automatically called when an object is created.
Example:
class Student {
Student() {
System.out.println("Object Created");
}
}
When an object is created:
Student student = new Student();
Output:
Why Do We Need Constructors?
Without constructors, every object would need to be initialized manually after creation.
Example without a constructor:
Student s = new Student();
s.id = 101;
s.name = "Rahul";
Using a constructor:
Student s = new Student(101, "Rahul");
Constructors make object creation easier and reduce repetitive code.
Rules of Constructors
A constructor follows these rules:
- The constructor name must be exactly the same as the class name.
- A constructor has no return type, not even void.
- Constructors are called automatically when an object is created.
- A class can have multiple constructors (constructor overloading).
- Constructors can have access modifiers such as public, private, or protected.
- Constructors cannot be inherited.
- Constructors can call other constructors using this().
- If no constructor is defined, Java provides a default constructor automatically.
Syntax of a Constructor
class ClassName {
ClassName() {
// Initialization code
}
}
Example:
class Employee {
Employee() {
System.out.println("Employee Object Created");
}
}
Default Constructor
A default constructor is a constructor that does not accept any parameters.
Example:
class Student {
Student()
System.out.println("Default Constructor Called");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
}
}
Output:
If you do not define any constructor, the Java compiler automatically provides a default constructor.
Parameterized Constructor
A parameterized constructor accepts parameters and initializes object fields with user-provided values.
Example:
class Student {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
void display() {
System.out.println(id + " " + name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(101, "Rahul");
s.display();
}
}
Output:
Constructor Overloading
A class can contain multiple constructors with different parameter lists.
Example:
class Employee {
Employee() {
System.out.println("Default Constructor")
}
Employee(String name) {
System.out.println(name);
}
Employee(int id, String name) {
System.out.println(id + " " + name);
}
}
Output:
Rahul
101 Rahul
Constructor overloading increases flexibility during object creation.
Constructor Chaining
Constructor chaining means calling one constructor from another constructor within the same class.
Example:
class Student {
Student() {
this(101);
System.out.println("Default Constructor");
}
Student(int id) {
System.out.println("ID: " + id);
}
}
Output:
Default Constructor
Constructor chaining avoids duplicate initialization code.
Using this() in Constructors
The this() keyword calls another constructor of the same class.
Example:
The this() keyword calls another constructor of the same class.
Example:
class Student {
Student() {
this("Rahul");
}
Student(String name) {
System.out.println(name);
}
}
Output:
Rules:
- this() must be the first statement inside a constructor.
- Only one constructor call (this() or super()) is allowed as the first statement.
Constructor vs Method
| Constructor | Method |
|---|---|
| Initializes objects | Performs operations |
| Same name as the class | Can have any valid name |
| No return type | Must have a return type or void |
| Called automatically | Called explicitly |
| Executes once per object creation | Can be called multiple times |
| Cannot be inherited | Can be inherited (depending on access modifier) |
Constructor Execution Flow
Class Definition
│
▼
Create Object using new
│
▼
Memory Allocated
│
▼
Constructor Invoked
│
▼
Object Initialized
│
▼
Object Ready for Use
Real-Life Example
Consider a Bank Account application.
Each account requires:
- Account Number
- Account Holder Name
- Initial Balance
Using a constructor:
class BankAccount {
int accountNumber;
String holderName;
double balance;
BankAccount(int accountNumber,
String holderName,
double balance) {
this.accountNumber = accountNumber;
this.holderName = holderName;
this.balance = balance;
}
}
Object creation:
BankAccount account =
new BankAccount(
1001,
"Rahul",
50000);
The object is fully initialized immediately after creation.
Advantages of Constructors
Constructors provide several benefits:
- Automatically initialize objects.
- Reduce repetitive code.
- Improve code readability.
- Ensure objects start in a valid state.
- Support constructor overloading.
- Work seamlessly with inheritance.
- Simplify object creation.
- Improve application maintainability.
Best Practices
Follow these best practices when using constructors:
- Initialize all required fields in constructors.
- Keep constructors focused on initialization only.
- Use constructor overloading for flexibility.
- Use this() to reuse initialization code.
- Prefer immutable objects when appropriate.
- Use meaningful parameter names.
- Validate constructor arguments before assigning them.
Conclusion
A Java constructor is a fundamental feature of Object-Oriented Programming that automatically initializes objects during their creation. By ensuring that every object starts with valid data, constructors improve code quality, readability, and maintainability. Java supports default constructors, parameterized constructors, constructor overloading, and constructor chaining, giving developers flexibility in how objects are initialized.
Java Constructor – Interview Questions
Q 1: What is a constructor in Java?
Q 2: Does constructor have a return type?
Q 3: When is constructor called?
Q 4: Can constructors be overloaded?
Q 5: What is default constructor?
Java Constructor – Objective Questions (MCQs)
Q1. What is a constructor in Java?
Q2. Which of the following has the same name as the class?
Q3. Which keyword is used to call one constructor from another in the same class?
Q4. What happens if a class has no constructor defined?
Q5. Which of the following statements about constructors is false?