Constructor in Java Explained: From Basics to Object Creation

Related Courses

Constructor in Java Explained: From Basics to Object Creation

You create an object in Java with the new keyword, but creating an object is only the first part of the job. Most objects need some information before they can be useful. A Student may need a name and roll number. An Employee may need an ID and department. An Order may need a customer and an order number.

One common way to provide that starting information is through a constructor.

Constructors are easy to recognize once you know their basic rules, but they also connect to several important Java concepts: object initialization, overloaded constructors, constructor chaining, inheritance, and class design. Understanding them properly makes later Java topics much easier to work with.

Table of Contents

  1. What Is a Constructor in Java?

  2. What Happens When an Object Is Created?

  3. Writing Your First Java Constructor

  4. Different Ways to Initialize Objects

  5. Constructor Overloading and Chaining

  6. Constructor vs Method: What Is the Difference?

  7. A Constructor in a Real Java Example

  8. Mistakes Beginners Commonly Make

  9. Why Constructors Matter in Java Development

  10. Frequently Asked Questions

  11. Conclusion

What Is a Constructor in Java?

A constructor in Java is a special part of a class that runs when an object is created. Its main job is to give the new object an initial state.

Consider a simple class:

class Student {
String name;
int rollNumber;

Student(String name, int rollNumber) {
this.name = name;
this.rollNumber = rollNumber;
}
}

The code named Student inside the class is a constructor. It has the same name as the class and accepts the information required to initialize a student.

An object can then be created like this:

Student student = new Student("Rahul", 101);

At that point, the constructor receives "Rahul" and 101 and stores those values in the new object's fields.

A Java constructor has a few characteristics worth remembering:

● Its name must match the class name.

● It does not have a return type.

● It is called when an object is created.

● A class can have multiple constructors.

● Constructors are commonly used to initialize instance variables.

That last point is particularly important. A constructor gives developers a convenient place to decide what an object should look like immediately after it comes into existence.

What Happens When an Object Is Created?

A line such as this looks simple:

Employee employee = new Employee("Anita", 501);

But several things happen as part of object creation.

Java needs to create space for the new Employee object. It then looks for a constructor that matches the arguments supplied after new Employee.

If the class contains:

class Employee {
String name;
int id;

Employee(String name, int id) {
this.name = name;
this.id = id;
}
}

the two arguments match the constructor, which is then executed for the newly created object.

The this keyword is useful in this situation. In:

this.name = name;

the first name refers to the instance variable belonging to the current object. The second name refers to the constructor parameter.

This naming pattern is common in Java because it keeps constructor parameters easy to understand.

Writing Your First Java Constructor

A constructor does not need to be complicated.

Here is a basic example:

class Laptop {

String brand;

Laptop() {
brand = "Unknown";
}
}

Now:

Laptop laptop = new Laptop();

creates a Laptop object and executes the no-argument constructor.

You can also provide information while creating the object:

class Laptop {

String brand;

Laptop(String brand) {
this.brand = brand;
}
}

The object can then be created as:

Laptop laptop = new Laptop("Lenovo");

The difference is simple: the first constructor decides the initial value internally, while the second receives that value from the code creating the object.

This is useful when different objects of the same class need different starting data.

Different Ways to Initialize Objects

Java supports several constructor patterns. The choice depends on what information the class needs.

No-Argument Constructor

A no-argument constructor accepts no parameters.

class Course {

Course() {
System.out.println("Course object created");
}
}

It can be called with:

Course course = new Course();

If you do not write any constructor at all, Java can provide a compiler-generated default constructor. However, there is an important detail here: once you write your own constructor, Java does not automatically add another no-argument constructor for you.

For example:

class Course {

Course(String name) {
// initialization
}
}

This class does not automatically have Course().

Trying to write:

Course course = new Course();

would result in a compilation error because no matching constructor exists.

Parameterized Constructor

A parameterized constructor accepts one or more values.

class Course {

String name;
int duration;

Course(String name, int duration) {
this.name = name;
this.duration = duration;
}
}

Now different objects can carry different information:

Course java = new Course("Java", 6);
Course python = new Course("Python", 4);

This approach is particularly useful when an object should not exist without certain basic information.

Copy-Constructor Style

Java does not have a special language feature called a copy constructor, but you can create a constructor that accepts another object of the same class.

class Account {

String holder;
double balance;

Account(String holder, double balance) {
this.holder = holder;
this.balance = balance;
}

Account(Account other) {
this.holder = other.holder;
this.balance = other.balance;
}
}

Then:

Account first = new Account("Priya", 5000);
Account second = new Account(first);

The second constructor reads values from the existing object and assigns them to the new one.

This technique is useful in some designs, although developers need to think carefully about what happens when a class contains references to other mutable objects. Copying a reference is different from creating a completely independent copy of the referenced object.

Default Constructor and No-Argument Constructor Are Not Always the Same

These terms are often mixed together.

A default constructor is supplied by the compiler when a class has no constructor declaration.

A no-argument constructor simply means a constructor that accepts zero arguments. It may be written by the programmer.

For example:

class Book {
}

can receive a compiler-provided default constructor.

But:

class Book {

Book() {
System.out.println("Book created");
}
}

contains a programmer-defined no-argument constructor.

Type

Accepts arguments?

Typical use

Compiler-provided default constructor

No

Basic object creation when no constructor is declared

No-argument constructor

No

Create an object without passing values

Parameterized constructor

Yes

Set initial values during object creation

Copy-constructor style

Usually another object

Initialize a new object from an existing object

Constructor Overloading and Chaining

Suppose a User object can be created with no information, just a name, or both a name and age.

You could write three constructors:

class User {

String name;
int age;

User() {
name = "Guest";
age = 0;
}

User(String name) {
this.name = name;
age = 0;
}

User(String name, int age) {
this.name = name;
this.age = age;
}
}

This is constructor overloading. The constructors have the same name but different parameter lists.

The following statements can therefore coexist:

User u1 = new User();
User u2 = new User("Arun");
User u3 = new User("Arun", 25);

There is another useful technique here: constructor chaining.

Instead of repeating initialization logic, one constructor can call another using this(...).

class User {

String name;
int age;

User() {
this("Guest", 0);
}

User(String name) {
this(name, 0);
}

User(String name, int age) {
this.name = name;
this.age = age;
}
}

The constructors now have a clear flow. The first two delegate the actual field initialization to the third constructor.

One rule is important: when this(...) is used to call another constructor in the same class, it must be the first statement in that constructor.

Constructor vs Method: What Is the Difference?

A constructor may look similar to a method because both can contain Java statements, but their purposes are different.

S.No

Constructor

Method

1

Initializes an object

Performs an operation

2

Uses the class name

Can have its own name

3

Has no return type

Has a return type or void

4

Runs as part of object creation

Usually called when needed

5

Establishes initial state

Usually represents object behavior

For example:

class BankAccount {

double balance;

BankAccount(double balance) {
this.balance = balance;
}

void deposit(double amount) {
balance += amount;
}
}

BankAccount() prepares the account when it is created. deposit() performs an action after the account already exists.

Keeping this distinction clear helps when designing classes. A constructor should generally deal with getting an object into a valid starting state rather than becoming a container for every operation the class might perform.

A Constructor in a Real Java Example

Consider a small application that keeps track of customer orders.

An order might need three pieces of information when it is created:

● Order ID

● Customer name

● Total amount

A simple class could look like this:

class Order {

int orderId;
String customerName;
double amount;

Order(int orderId, String customerName, double amount) {
this.orderId = orderId;
this.customerName = customerName;
this.amount = amount;
}
}

Creating an order becomes straightforward:

Order order = new Order(1001, "Ravi", 2499.50);

The object now starts life with its basic information already assigned.

Imagine the same application without a parameterized constructor. A developer might create an empty object and then remember to assign each field separately. That approach can work, but it makes it easier to create incomplete objects accidentally.

In a larger project, constructors are often part of the class design rather than something added just to satisfy a Java syntax rule. The developer has to think about which information is essential and which information can be supplied later.

That is where constructors become more interesting: they encourage you to think about the valid starting state of an object.

Mistakes Beginners Commonly Make

One of the most frequent errors is accidentally giving a constructor a return type.

This:

void Student() {

}

 

is not a constructor. It is a method named Student.

The constructor would be:

Student() {

}

Another common mistake is expecting Java to provide a no-argument constructor after a parameterized constructor has been declared.

For example:

class Student {

 

    Student(String name) {

        // ...

    }

}

 

does not provide Student() automatically.

Another issue appears when constructor parameters do not match the values supplied during object creation. If the only available constructor is:

Product(String name, double price)

 

then:

new Product("Keyboard");

 

does not match it.

There is also a design mistake worth mentioning: putting too much work inside a constructor. Constructors are a good place for initial setup, but complicated database operations, long-running tasks, or unrelated business logic can make objects harder to test and maintain.

A useful question is: What does this object absolutely need at the moment it is created? That is usually a good starting point for deciding what belongs in the constructor.

Why Constructors Matter in Java Development

Constructors appear throughout object-oriented Java programming. They are used in simple practice programs, business applications, APIs, libraries, and frameworks.

For someone learning Java professionally, constructor concepts also prepare the ground for larger topics. Once you understand how objects are initialized, concepts such as inheritance, encapsulation, dependency injection, and object-oriented design become easier to reason about.

The best way to learn constructors is not to memorize all the definitions at once.

Create a small class yourself.

Start with a Student class. Give it a no-argument constructor. Add a constructor that accepts a name. Then add another that accepts a name and roll number. Finally, try using this(...) to connect the constructors.

That small exercise exposes several Java rules in a few lines of code.

Conclusion

A constructor is more than a special method-like block of code. It is the starting point for an object's state.

Once you understand how a constructor works, the differences between no-argument and parameterized constructors become straightforward. From there, constructor overloading and chaining provide useful ways to handle different object-creation requirements.

For anyone learning Java, a good next exercise is to build three small classes such as Student, Product, and Employee and decide which values each object should receive at creation time.

When designing an Employee class, which fields would you require through the constructor, and which would you allow the object to receive later?

Follow NareshIT for more practical insights on technology, skills, and career development.

Frequently Asked Questions

1. What is a constructor in Java?

A constructor is a special part of a Java class that executes during object creation. It has the same name as the class and does not have a return type. It is commonly used to initialize an object's starting state.

2. Can a class have more than one constructor?

Yes. Java supports constructor overloading, so a class can contain multiple constructors as long as their parameter lists are different.

3. Does a constructor return a value?

No. Constructors do not have return types. If void, int, or another return type is added, Java treats the declaration as a method rather than a constructor.

4. What happens when no constructor is declared?

If a class contains no constructor declaration, Java can provide a default no-argument constructor. If you declare a constructor yourself, any additional constructor you need must be declared explicitly.

5. Can constructors be inherited by a child class?

No. Constructors are not inherited. When an object of a subclass is created, Java handles constructor execution through the class hierarchy according to the constructors defined in the superclass and subclass.