惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
L
LangChain Blog
H
Help Net Security
博客园_首页
T
Tailwind CSS Blog
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
雷峰网
雷峰网
Recent Announcements
Recent Announcements
D
DataBreaches.Net
U
Unit 42
Vercel News
Vercel News
I
InfoQ
Martin Fowler
Martin Fowler
Microsoft Azure Blog
Microsoft Azure Blog
Apple Machine Learning Research
Apple Machine Learning Research
S
SegmentFault 最新的问题
Jina AI
Jina AI
博客园 - 叶小钗
博客园 - 【当耐特】
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
Last Week in AI
Last Week in AI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Constructors in Java: Why Do We Need Them?
Kathirvel S · 2026-06-02 · via DEV Community

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;

No problem.

Now let's create another product.

SuperMarket product2 = new SuperMarket();

product2.name = "Sugar";
product2.price = 150;

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

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);

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);

How does Java know where to store:

"product1's name"

and

200

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;

}

Now you write:

SuperMarket product1 =
        new SuperMarket("product1's name", 200);

Java immediately gets confused.

It starts searching for a constructor that accepts:

(String, int)

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

Why?

Because Java only knows how to create:

new SuperMarket();

not

new SuperMarket("product1's name", 200);


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;

    }
}

Now the error disappears.

You can create:

SuperMarket product1 =
        new SuperMarket("product1's name", 200);

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;

}

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)

Java creates local variables:

name
price

These belong only to the constructor.

Now look at:

name = name;

Java sees:

localName = localName;

Similarly:

price = price;

becomes:

localPrice = localPrice;

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;

    }
}

Now:

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

System.out.println(product1.name);
System.out.println(product1.price);

Output:

null
0

Expected:

Rice
200

Actual:

null
0

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;

}

Now:

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

Java does:

this.name = "Rice";
this.price = 200;

Now values are stored properly.


Output After Fixing

System.out.println(product1.name);
System.out.println(product1.price);

Output:

Rice
200

Perfect.


Constructor Rule #1

Constructor Name Must Be Same As Class Name

Class:

class SuperMarket

Constructor:

public SuperMarket()
{
}

Notice both names are identical.


Wrong

public Market()
{
}

Error:

invalid method declaration;
return type required

Why?

Java thinks this is a normal method.

Since methods require a return type, Java complains.


Correct

public SuperMarket()
{
}

Constructor name matches class name.

No error.


Constructor Rule #2

No Return Type Required

Methods require return types.

Example:

public void display()
{
}

But constructors are different.

Correct

public SuperMarket()
{
}

No return type.


Wrong

public void SuperMarket()
{
}

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();

The moment Java sees:

new SuperMarket()

it automatically executes the constructor.

You don't need:

product1.SuperMarket();

In fact, that's impossible.

Java automatically calls the constructor during object creation.


Proof

class SuperMarket {

    public SuperMarket() {

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

    }
}

Object creation:

SuperMarket product1 =
        new SuperMarket();

Output:

Constructor Executed

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);

Each object gets different values instantly.

That's called object initialization.


What Happens When We Write This?

SuperMarket product1 =
        new SuperMarket();

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;

}

Notice:

No constructor is written.

Now:

SuperMarket product1 =
        new SuperMarket();

Works perfectly.

Why?

Because Java secretly creates a constructor for you.

Something like:

public SuperMarket()
{
}

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;

}

SuperMarket product1 =
        new SuperMarket();

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;

    }
}

Now try:

SuperMarket product1 =
        new SuperMarket();

Error:

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

required: String,int
found: no arguments

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;

    }
}

Now both work:

new SuperMarket();

and

new SuperMarket("Rice", 200);

No errors.


Real-World Benefit of Constructors

Without constructor:

SuperMarket product =
        new SuperMarket();

product.name = "Rice";
product.price = 200;

With constructor:

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

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;

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/