In Java, when we create an object of a class, it’s important to assign initial values to its variables so that the object can begin with a valid state. This initialization process is handled by constructors.
A constructor is a special block of code in Java that is automatically executed when a new object of a class is created using the new keyword. Unlike regular methods, constructors are not called explicitly and do not have a return type—not even void.
Constructors play a fundamental role in object-oriented programming because they allow you to:
- Assign initial values to fields (variables) of the class.
- Enforce object creation rules.
- Execute necessary setup code at the moment the object is created.
Simply put: A constructor is the “entry point” to setting up a new object with its initial characteristics or data.
What is constructor?
A constructor in Java is a special, non-static block of code with the same name as the class, which is invoked automatically when an object of that class is instantiated.
Here’s what makes constructors unique and important:
1. Same Name as Class
A constructor must have the same name as the class in which it is defined. This is how the compiler identifies it as a constructor and not a method.
class Car {
Car() { // Constructor: name matches class name
System.out.println("Car object created.");
}
}
2. No Return Type
Constructors do not return any value, not even void. Adding a return type makes it a method, not a constructor.
// This is a method, not a constructor
Car void Car() { ... } ❌ Invalid Constructor
3. Automatically Invoked
A constructor is automatically called when an object is created using the new keyword.
Car myCar = new Car(); // Constructor is invoked here
4. Used for Initialization
Constructors are used to:
- Assign values to class variables.
- Prepare the object for use.
- Run setup code or validation logic.
5. Can Be Overloaded
You can define multiple constructors in the same class with different parameters (constructor overloading), allowing for flexible object creation.
Real-World Analogy of Constructor
Think of a constructor like the blueprint setup function for a newly constructed house. Before someone can live in the house:
- The walls must be built.
- The rooms must be numbered.
- The default furniture or appliances must be placed.
Similarly, a constructor prepares the object’s “internal setup” before it can be used in a program.
Java Constructor Example 1: no constructor is explicitly defined
When there is no constructor is explicitly defined in the class.
In such cases, Java automatically provides a default constructor behind the scenes — this is known as the compiler-generated default constructor.
class Student {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student(); // Default constructor is automatically called
s1.displayInfo();
}
}
Output:
Name: null
Age: 0
Step-by-Step Explanation
Step 1: Class and Variables
class Student {
String name;
int age;
nameandageare instance variables.nameis a reference type (String) — default value isnull.ageis a primitive type (int) — default value is0.
Step 2: No Constructor is Defined
There is no constructor defined in the class.
Java automatically provides the following default constructor internally:
Student() {
// compiler-generated default constructor
}
- This default constructor does not set any values.
- It leaves the fields to their default Java values:
String→nullint→0boolean→false- Object references →
null
Step 3: Creating the Object
Student s1 = new Student();
- Java invokes the default constructor.
s1.name=null,s1.age=0.
Step 4: Display Method
s1.displayInfo();
- Displays the default values of the variables:
Name: null
Age: 0
Key Note
If you define any constructor (like parameterized or non-parameterized), Java will NOT provide the default constructor. You’ll need to define it yourself if needed.
Java Constructor Example 2: Non-Parameterized Constructor
class Student {
String name;
int age;
// Non-Parameterized Constructor
Student() {
name = "Unknown";
age = 0;
System.out.println("Non-parameterized constructor called.");
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student(); // Constructor gets called
s1.displayInfo();
}
}
Output:
Non-parameterized constructor called.
Name: Unknown, Age: 0
Step-by-Step Explanation
Step 1: Class and Variables Declaration
class Student {
String name;
int age;
- The class
Studentis declared. - Two instance variables
name(String) andage(int) are declared. These will be unique for every object.
Step 2: Non-Parameterized Constructor Definition
- This is a user-defined constructor that does not take any parameters.
- Inside the constructor:
nameis initialized with the default value"Unknown".ageis initialized with the value0.
- A message is printed to confirm that the constructor was called.
⚠️ If you don’t define any constructor in your class, Java automatically provides a default constructor (also non-parameterized). But if you define even one constructor (like this), Java doesn’t create any default one.
Step 3: Display Method
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
- This method prints the values stored in the instance variables
nameandage.
Step 4: Object Creation & Method Call
public static void main(String[] args) {
Student s1 = new Student(); // Constructor gets called
s1.displayInfo();
}
- Inside the
main()method:Student s1 = new Student();creates an object of classStudent.- The non-parameterized constructor is automatically called.
- It initializes the values of
nameandage.
- Then,
s1.displayInfo();prints those initialized values.
Java Constructor Example 3: Parameterized Constructor
class Student {
String name;
int age;
// Constructor
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student("Priya", 21); // Constructor gets called
s1.displayInfo();
}
}
Output:
Name: Priya, Age: 21
Step-by-Step Breakdown
Step 1: Class and Variables Declaration
class Student {
String name;
int age;
- A class named
Studentis defined. - Two instance variables
name(typeString) andage(typeint) are declared. - These variables are unique for each object created from the
Studentclass.
Step 2: Constructor Definition
Student(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
This is a parameterized constructor because it takes arguments.
It is automatically called when an object of Student is created using new Student(...).
Inside the constructor:
studentNameandstudentAgeare parameters (local variables).name = studentName;assigns the parameter value to the instance variablename.age = studentAge;assigns the parameter value to the instance variableage.
Step 3: Method to Display Data
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
- A regular method
displayInfo()is defined to print the student’s name and age. - It accesses the instance variables
nameandage.
Step 4: Main Method & Object Creation
public static void main(String[] args) {
Student s1 = new Student("Priya", 21); // Constructor gets called
s1.displayInfo();
}
main()is the entry point of the program.Student s1 = new Student("Priya", 21);creates a new objects1of classStudent.- This triggers the constructor with the values:
studentName = "Priya"studentAge = 21
- Inside the constructor:
name = "Priya"age = 21
- So now, the object
s1has:s1.name → "Priya"s1.age → 21
Step 5: Calling Method on Object
s1.displayInfo();
- Calls the method
displayInfo()on objects1. - It prints the instance variable values stored in
s1.
Calling One Constructor from Another
In Java, the this() keyword is used to call one constructor from another within the same class. This is known as constructor chaining. It helps avoid code duplication by reusing constructor logic. The call to this() must be the first statement in the constructor.
In the given example, when new Car() is called, the default constructor internally calls the parameterized constructor Car(String model) using this("BMW"). As a result, the program first prints the car model, followed by the message from the default constructor, demonstrating how one constructor can delegate object initialization to another.
class Car {
Car() {
this("BMW"); // Calls the parameterized constructor
System.out.println("Default constructor");
}
Car(String model) {
System.out.println("Car model: " + model);
}
public static void main(String[] args) {
Car c = new Car(); // Default constructor is called
}
}
Output:
Car model: BMW
Default constructor
Step-by-Step Explanation
Step 1: Constructor Chaining with this()
- The keyword
this()is used to call another constructor from within the same class. - It must be the first statement in the constructor.
- It allows you to avoid repeating initialization code by reusing constructors.
Step 2: What Happens in main()?
Car c = new Car();
- You are creating an object
cusing the default constructor:Car(). - So Java calls:
Car() { this("BMW");
System.out.println("Default constructor"); }
Step 3: Inside the Default Constructor
- The first line is
this("BMW");— this means:- The parameterized constructor
Car(String model)is called with"BMW"as the argument.
- The parameterized constructor
So the control jumps to:
Car(String model) {
System.out.println("Car model: " + model);
}
Step 4: Execution of Parameterized Constructor
- The string
"BMW"is passed. - The line:
System.out.println("Car model: " + model);
- prints:
Car model: BMW
- After this constructor completes, control goes back to the default constructor, and the next line runs: javaCopyEdit
System.out.println("Default constructor");
This prints:
Default constructor
Summary
| Order | What Happens | Output |
|---|---|---|
| 1 | Car() called | |
| 2 | Inside Car(), this("BMW") calls parameterized constructor | |
| 3 | Car(String model) prints model | Car model: BMW |
| 4 | Back to Car(), prints message | Default constructor |
Key Rule: Use of this() in Constructor
this()calls another constructor in the same class.- Must be the first line inside the constructor.
- Helps in constructor chaining to avoid code duplication.
Use Case
Use this() when:
- You want to reuse constructor logic.
- You have multiple constructors with shared initialization steps.
🧬 Constructor vs Method
| Feature | Constructor | Method |
|---|---|---|
| Name | Same as class | Any name |
| Return Type | None | Must have a return type |
| Call | Called automatically | Called manually |
| Purpose | Initialize object | Define behavior |
❓ Frequently Asked Questions (FAQs)
Q1: Can a constructor be static?
No. Constructors are used to create objects, and static belongs to the class, not instances.
Q2: Can a constructor be final, abstract, or synchronized?
No. Constructors cannot be declared as final, abstract, or synchronized.
Q3: Is it possible to call a constructor explicitly?
Only by using this() or super(), not like normal methods.
Q4: What happens if we don’t define a constructor?
Java provides a default constructor.
Q5: Can we overload constructors?
Yes. Constructor Overloading is a common practice in Java.
Q6: What is the role of this() in constructors?
To invoke another constructor in the same class. It must be the first statement in the constructor.
Q7: Can we use return inside a constructor?
Yes, but only return; with no value (to exit early). You cannot return a value.
Q8: What is the difference between this() and super()?
this()calls another constructor in the same class.super()calls the parent class constructor.
Q9: Can we have private constructors?
Yes. Used in Singleton design patterns or utility classes.
class MyClass {
private MyClass() {
System.out.println("Private constructor");
}
}
Q10: Can a constructor throw exceptions?
Yes, like any method:
class Demo {
Demo() throws Exception {
throw new Exception("Error in constructor");
}
}
🧠 Practice Exercise
Write a class BankAccount with:
- A default constructor setting balance to 1000
- A parameterized constructor to set a custom balance
- A method
showBalance()to display the balance
Try it on your own and verify the output.
📌 Summary
- Constructors initialize objects.
- Can be default, parameterized, overloaded, or copy.
- Have no return type.
- Automatically called when an object is created.
- Use
this()andsuper()to manage constructor chaining.