DEV Community

Cover image for Constructors in Java: Why Do We Need Them?
Kathirvel S
Kathirvel S

Posted on

Constructors in Java: Why Do We Need Them?

Introduction

Imagine you are building a supermarket management system in Java.

You create a class called SuperMarket to represent products.

Let's say every product has:

  • A name
  • A price

At first, everything seems easy.

SuperMarket product1 = new SuperMarket();

product1.name = "Rice";
product1.price = 200;
Enter fullscreen mode Exit fullscreen mode

No problem.

Now let's create another product.

SuperMarket product2 = new SuperMarket();

product2.name = "Sugar";
product2.price = 150;
Enter fullscreen mode Exit fullscreen mode

Still looks fine.

But wait...

What if your supermarket has 2,000 products?

SuperMarket product1 = new SuperMarket();
product1.name = "Rice";
product1.price = 200;

SuperMarket product2 = new SuperMarket();
product2.name = "Sugar";
product2.price = 150;

SuperMarket product3 = new SuperMarket();
product3.name = "Milk";
product3.price = 60;

SuperMarket product4 = new SuperMarket();
product4.name = "Tea";
product4.price = 120;

// ... imagine doing this 2000 times
Enter fullscreen mode Exit fullscreen mode

Looks exhausting, right?

For every object:

  1. Create object
  2. Set name
  3. Set price

Again and again.

This is repetitive.

This is error-prone.

This is exactly the problem that constructors solve.


The Better Way

Instead of creating an object first and then assigning values manually, Java allows us to provide values during object creation itself.

SuperMarket product1 = new SuperMarket("product1's name", 200);
Enter fullscreen mode Exit fullscreen mode

Now think about it.

In one line:

  • Object is created
  • Name is assigned
  • Price is assigned

Much cleaner.

Much faster.

Much safer.

But when beginners see this line, they often ask:

"Wait... where did those values go?"

SuperMarket product1 = new SuperMarket("product1's name", 200);
Enter fullscreen mode Exit fullscreen mode

How does Java know where to store:

"product1's name"
Enter fullscreen mode Exit fullscreen mode

and

200
Enter fullscreen mode Exit fullscreen mode

The answer is:

Constructor


What Is a Constructor?

Official Definition

A constructor is a special member of a class that is automatically called when an object is created and is used to initialize objects.

Reference

Oracle Java Documentation describes constructors as special members of a class that are used to initialize objects and are automatically invoked when an object is created.

Source:
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html


Beginner-Friendly Definition

A constructor is a special method that runs automatically when we create an object and helps us give initial values to that object.

Think of it like this:

When a new employee joins a company, some information must be collected immediately:

  • Name
  • Employee ID
  • Department

Similarly, when a new object is created, some values may be required immediately.

A constructor helps us provide those values at the time of object creation.


The Problem You'll Face

Suppose your class looks like this:

class SuperMarket {

    String name;
    int price;

}
Enter fullscreen mode Exit fullscreen mode

Now you write:

SuperMarket product1 =
        new SuperMarket("product1's name", 200);
Enter fullscreen mode Exit fullscreen mode

Java immediately gets confused.

It starts searching for a constructor that accepts:

(String, int)
Enter fullscreen mode Exit fullscreen mode

But your class doesn't have one.

So Java throws an error.

Error

constructor SuperMarket in class SuperMarket
cannot be applied to given types;

required: no arguments
found: String,int
reason: actual and formal argument lists differ in length
Enter fullscreen mode Exit fullscreen mode

Why?

Because Java only knows how to create:

new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

not

new SuperMarket("product1's name", 200);
Enter fullscreen mode Exit fullscreen mode

Solving the Error Using a Constructor

Let's create a constructor.

class SuperMarket {

    String name;
    int price;

    public SuperMarket(String name, int price) {

        name = name;
        price = price;

    }
}
Enter fullscreen mode Exit fullscreen mode

Now the error disappears.

You can create:

SuperMarket product1 =
        new SuperMarket("product1's name", 200);
Enter fullscreen mode Exit fullscreen mode

But wait...

A new problem appears.


The Silent Bug

Many beginners think this code is correct.

public SuperMarket(String name, int price) {

    name = name;
    price = price;

}
Enter fullscreen mode Exit fullscreen mode

Looks correct.

No compilation error.

No red underline.

No warning.

But it DOES NOT work.

Let's understand why.


Why name = name Does Not Work

Inside the constructor:

public SuperMarket(String name, int price)
Enter fullscreen mode Exit fullscreen mode

Java creates local variables:

name
price
Enter fullscreen mode Exit fullscreen mode

These belong only to the constructor.

Now look at:

name = name;
Enter fullscreen mode Exit fullscreen mode

Java sees:

localName = localName;
Enter fullscreen mode Exit fullscreen mode

Similarly:

price = price;
Enter fullscreen mode Exit fullscreen mode

becomes:

localPrice = localPrice;
Enter fullscreen mode Exit fullscreen mode

You're assigning a variable to itself.

Nothing gets stored inside the object.

Reference

The this keyword refers to the current object. It is commonly used when constructor parameters have the same names as instance variables, allowing Java to distinguish between them.

Source:
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html


Proof

class SuperMarket {

    String name;
    int price;

    public SuperMarket(String name, int price) {

        name = name;
        price = price;

    }
}
Enter fullscreen mode Exit fullscreen mode

Now:

SuperMarket product1 =
        new SuperMarket("Rice", 200);

System.out.println(product1.name);
System.out.println(product1.price);
Enter fullscreen mode Exit fullscreen mode

Output:

null
0
Enter fullscreen mode Exit fullscreen mode

Expected:

Rice
200
Enter fullscreen mode Exit fullscreen mode

Actual:

null
0
Enter fullscreen mode Exit fullscreen mode

Why?

Because object variables never received the values.


The Correct Solution

Use this.

public SuperMarket(String name, int price) {

    this.name = name;
    this.price = price;

}
Enter fullscreen mode Exit fullscreen mode

Now:

SuperMarket product1 =
        new SuperMarket("Rice", 200);
Enter fullscreen mode Exit fullscreen mode

Java does:

this.name = "Rice";
this.price = 200;
Enter fullscreen mode Exit fullscreen mode

Now values are stored properly.


Output After Fixing

System.out.println(product1.name);
System.out.println(product1.price);
Enter fullscreen mode Exit fullscreen mode

Output:

Rice
200
Enter fullscreen mode Exit fullscreen mode

Perfect.


Constructor Rule #1

Constructor Name Must Be Same As Class Name

Class:

class SuperMarket
Enter fullscreen mode Exit fullscreen mode

Constructor:

public SuperMarket()
{
}
Enter fullscreen mode Exit fullscreen mode

Notice both names are identical.


Wrong

public Market()
{
}
Enter fullscreen mode Exit fullscreen mode

Error:

invalid method declaration;
return type required
Enter fullscreen mode Exit fullscreen mode

Why?

Java thinks this is a normal method.

Since methods require a return type, Java complains.


Correct

public SuperMarket()
{
}
Enter fullscreen mode Exit fullscreen mode

Constructor name matches class name.

No error.


Constructor Rule #2

No Return Type Required

Methods require return types.

Example:

public void display()
{
}
Enter fullscreen mode Exit fullscreen mode

But constructors are different.

Correct

public SuperMarket()
{
}
Enter fullscreen mode Exit fullscreen mode

No return type.


Wrong

public void SuperMarket()
{
}
Enter fullscreen mode Exit fullscreen mode

This is NOT a constructor.

This becomes a normal method.

Java will not call it automatically.

Many beginners accidentally make this mistake.


Constructor Rule #3

Constructor Is Called Automatically

Look at:

SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

The moment Java sees:

new SuperMarket()
Enter fullscreen mode Exit fullscreen mode

it automatically executes the constructor.

You don't need:

product1.SuperMarket();
Enter fullscreen mode Exit fullscreen mode

In fact, that's impossible.

Java automatically calls the constructor during object creation.


Proof

class SuperMarket {

    public SuperMarket() {

        System.out.println("Constructor Executed");

    }
}
Enter fullscreen mode Exit fullscreen mode

Object creation:

SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

Output:

Constructor Executed
Enter fullscreen mode Exit fullscreen mode

See?

We never called it manually.

Java called it automatically.


Constructor Rule #4

Used For Initializing Objects With Specific Values

Suppose every product should have:

  • Name
  • Price

immediately after creation.

Constructor makes this possible.

SuperMarket product1 =
        new SuperMarket("Rice", 200);

SuperMarket product2 =
        new SuperMarket("Sugar", 150);

SuperMarket product3 =
        new SuperMarket("Milk", 60);
Enter fullscreen mode Exit fullscreen mode

Each object gets different values instantly.

That's called object initialization.


What Happens When We Write This?

SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

Interesting question.

Does Java create a constructor automatically?

The answer is:

YES... but only in certain situations.


Default Constructor

Suppose your class is:

class SuperMarket {

    String name;
    int price;

}
Enter fullscreen mode Exit fullscreen mode

Notice:

No constructor is written.

Now:

SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

Works perfectly.

Why?

Because Java secretly creates a constructor for you.

Something like:

public SuperMarket()
{
}
Enter fullscreen mode Exit fullscreen mode

This is called the Default Constructor.

Reference

According to the Java Language Specification, if a class contains no constructor declarations, the Java compiler automatically provides a default constructor. Once a programmer explicitly defines a constructor, the compiler no longer generates the default constructor automatically.

Source:
https://docs.oracle.com/javase/specs/


Proof

This works:

class SuperMarket {

    String name;
    int price;

}
Enter fullscreen mode Exit fullscreen mode
SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

No error.

Meaning Java generated a constructor behind the scenes.


Important Twist

Now write your own constructor.

class SuperMarket {

    String name;
    int price;

    public SuperMarket(String name, int price) {

        this.name = name;
        this.price = price;

    }
}
Enter fullscreen mode Exit fullscreen mode

Now try:

SuperMarket product1 =
        new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

Error:

constructor SuperMarket in class SuperMarket
cannot be applied to given types;

required: String,int
found: no arguments
Enter fullscreen mode Exit fullscreen mode

Why?

Because once you create your own constructor, Java stops generating the default constructor.

This surprises many beginners.


How To Fix This Error

Create your own no-argument constructor.

class SuperMarket {

    String name;
    int price;

    public SuperMarket() {

    }

    public SuperMarket(String name, int price) {

        this.name = name;
        this.price = price;

    }
}
Enter fullscreen mode Exit fullscreen mode

Now both work:

new SuperMarket();
Enter fullscreen mode Exit fullscreen mode

and

new SuperMarket("Rice", 200);
Enter fullscreen mode Exit fullscreen mode

No errors.


Real-World Benefit of Constructors

Without constructor:

SuperMarket product =
        new SuperMarket();

product.name = "Rice";
product.price = 200;
Enter fullscreen mode Exit fullscreen mode

With constructor:

SuperMarket product =
        new SuperMarket("Rice", 200);
Enter fullscreen mode Exit fullscreen mode

Cleaner.

Shorter.

Less code.

Less mistakes.

More professional.

And when your project contains thousands of objects, constructors save a huge amount of time.


Conclusion

We started with manually assigning values to every object:

product1.name = "Rice";
product1.price = 200;
Enter fullscreen mode Exit fullscreen mode

This works for a few objects but becomes difficult when dealing with hundreds or thousands of products.

To solve this problem, Java provides constructors.

A constructor:

  • Has the same name as the class
  • Does not need a return type
  • Runs automatically when an object is created
  • Helps initialize objects with specific values

We also learned:

  • Why name = name is a bug
  • Why this.name = name works
  • How constructors are automatically called
  • What a default constructor is
  • When Java creates a default constructor
  • Why the default constructor disappears after creating our own constructor
  • How to fix related errors

Once you understand constructors, object creation in Java becomes much more organized, cleaner, and easier to manage—especially in real-world applications where classes may create thousands of objects.


References

  1. Oracle Java Tutorials – Constructors

https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

  1. Oracle Java Tutorials – The this Keyword

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

  1. Oracle Java Tutorials – Classes and Objects

https://docs.oracle.com/javase/tutorial/java/javaOO/

  1. Java Language Specification (JLS)

https://docs.oracle.com/javase/specs/

  1. Oracle Java Documentation

https://docs.oracle.com/en/java/

Top comments (0)