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

推荐订阅源

N
Netflix TechBlog - Medium
S
Secure Thoughts
aimingoo的专栏
aimingoo的专栏
量子位
F
Full Disclosure
云风的 BLOG
云风的 BLOG
D
Docker
Stack Overflow Blog
Stack Overflow Blog
Last Week in AI
Last Week in AI
Security Latest
Security Latest
Project Zero
Project Zero
Cyberwarzone
Cyberwarzone
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
AWS News Blog
AWS News Blog
G
GRAHAM CLULEY
T
Threat Research - Cisco Blogs
The Hacker News
The Hacker News
The Register - Security
The Register - Security
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MyScale Blog
MyScale Blog
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
P
Privacy & Cybersecurity Law Blog
V
Visual Studio Blog
A
Arctic Wolf
L
LINUX DO - 热门话题
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
TaoSecurity Blog
TaoSecurity Blog
Recorded Future
Recorded Future
K
Kaspersky official blog
L
Lohrmann on Cybersecurity
V
V2EX
Recent Announcements
Recent Announcements
N
News and Events Feed by Topic
MongoDB | Blog
MongoDB | Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
S
Securelist
S
Security Affairs
Forbes - Security
Forbes - Security
P
Proofpoint News Feed
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
AI
AI
Vercel News
Vercel News
博客园 - 三生石上(FineUI控件)
Cisco Talos Blog
Cisco Talos Blog
T
Tor Project blog
Scott Helme
Scott Helme
Spread Privacy
Spread Privacy

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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/