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

推荐订阅源

腾讯CDC
Microsoft Azure Blog
Microsoft Azure Blog
B
Blog
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
MyScale Blog
MyScale Blog
A
About on SuperTechFans
雷峰网
雷峰网
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
The Cloudflare Blog
F
Fortinet All Blogs
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
宝玉的分享
宝玉的分享
罗磊的独立博客
量子位
有赞技术团队
有赞技术团队
V
V2EX
Engineering at Meta
Engineering at Meta

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
Java Constructors Demystified: What Happens Before Your O...
Hariharan S J · 2026-06-02 · via DEV Community

1.Introduction

Have you ever wondered what actually happens when you write:

SuperMarket product = new SuperMarket("Noodles", 50);

Enter fullscreen mode Exit fullscreen mode

We all know that an object gets created. But what happens behind the scenes? Where does the memory come from? When are the values assigned? And why does Java automatically call a constructor without us explicitly invoking it?

When I first learned constructors, I thought they were just special methods used to initialize objects. But after experimenting with object creation, default values, the this keyword, and constructor parameters, I discovered that constructors are much more than that—they are the starting point of an object's lifecycle.

In this blog, we'll go beyond the textbook definition of constructors. We'll explore what really happens when an object is created, why this is important, how Java assigns default values, and some beginner mistakes that can silently break your code.

By the end of this article, you'll not only know what a constructor is, but also why it behaves the way it does behind the scenes.

Let's create our first object and uncover the magic that happens the moment we use the new keyword.

2.What is a Constructor?

A constructor is used in the creation of an object that is an instance of a class. Typically it performs operations required to initialize the class before methods are invoked or fields are accessed. Constructors are never inherited.

A constructor in Java is a special member that is called when an object is created. It initializes the new object’s state. It is used to set default or user-defined values for the object's attributes

A constructor in Java is a special method that is used to initialize objects.

The constructor is called when an object of a class is created.

It can be used to set initial values for object attributes:

A constructor is a special block of code that runs automatically whenever an object is created.

Syntax

class SuperMarket {

    SuperMarket() {
        System.out.println("Constructor Called");
    }
}

Enter fullscreen mode Exit fullscreen mode

Creating an Object

SuperMarket product = new SuperMarket();

Enter fullscreen mode Exit fullscreen mode

Output

Constructor Called

Enter fullscreen mode Exit fullscreen mode

The moment the object is created using the new keyword, Java automatically invokes the constructor.

3.Rules of a Constructor

A constructor has a few important rules:

1. Constructor name must be the same as the class name

class SuperMarket {

    SuperMarket() {

    }
}

Enter fullscreen mode Exit fullscreen mode

2. Constructors do not have a return type

Correct

SuperMarket() {

}

Enter fullscreen mode Exit fullscreen mode

Incorrect

void SuperMarket() {

}

Enter fullscreen mode Exit fullscreen mode

The second example is not a constructor. It is a normal method.

4.Why Do We Need Constructors?

Imagine creating an object and manually assigning values every time.

SuperMarket product1 = new SuperMarket();
product1.name = "Noodles";
product1.price = 50;

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

Enter fullscreen mode Exit fullscreen mode

This works, but it becomes repetitive.

Instead, constructors allow us to initialize object-specific values immediately during object creation.

class SuperMarket {

    String name;
    int price;

    SuperMarket(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

Enter fullscreen mode Exit fullscreen mode

Now we can simply write:

SuperMarket product1 = new SuperMarket("Noodles", 50);
SuperMarket product2 = new SuperMarket("Shampoo", 150);

Enter fullscreen mode Exit fullscreen mode

Cleaner, safer, and easier to maintain.

5.Why Is the Constructor Called Twice?

Consider this code:

SuperMarket product1 = new SuperMarket("abc", 20);
SuperMarket product2 = new SuperMarket("xyz", 2000);

Enter fullscreen mode Exit fullscreen mode

Constructor:

SuperMarket(String name, int price) {
    System.out.println("Are you constructor?");
}

Enter fullscreen mode Exit fullscreen mode

Output:

Are you constructor?
Are you constructor?

Enter fullscreen mode Exit fullscreen mode

Many beginners get confused here.

The reason is simple:

  • One object = One constructor call

  • Two objects = Two constructor calls

Every time you use the new keyword, Java creates a new object and invokes the constructor.

6.The Mystery of this

Consider the following code:

class SuperMarket {

    String name;
    int price;

    SuperMarket(String name, int price) {
        this.name = name;
        this.price = price;
    }
}

Enter fullscreen mode Exit fullscreen mode

Here:

this.name

Enter fullscreen mode Exit fullscreen mode

refers to the instance variable.

While:

name

Enter fullscreen mode Exit fullscreen mode

refers to the constructor parameter.

So:

this.name = name;

Enter fullscreen mode Exit fullscreen mode

Means:

instanceVariable = parameter;

Enter fullscreen mode Exit fullscreen mode

7.What Happens If We Remove this?

Suppose we write:

SuperMarket(String name, int price) {
    name = name;
    price = price;
}

Enter fullscreen mode Exit fullscreen mode

At first glance, it looks correct.

But Java interprets it as:

parameter = parameter;
parameter = parameter;

Enter fullscreen mode Exit fullscreen mode

The instance variables never receive the values.

8.Then Why Do We See null and 0?

Let's look at the class:

class SuperMarket {

    String name;
    int price;
}

Enter fullscreen mode Exit fullscreen mode

Even though we never assigned values, Java still prints:

null
0

Enter fullscreen mode Exit fullscreen mode

Why?

Because Java automatically assigns default values to instance variables.

9.What Actually Happens During Object Creation?

When Java executes:

new SuperMarket("Noodles", 50);

Enter fullscreen mode Exit fullscreen mode

The JVM follows these steps:

Step 1

Memory is allocated for the object.

Step 2

Default values are assigned.

name = null
price = 0

Enter fullscreen mode Exit fullscreen mode

Step 3

Field initializers are executed (if any).

String name = "Python";

Enter fullscreen mode Exit fullscreen mode

Step 4

Constructor executes.

SuperMarket(String name, int price) {
    this.name = name;
    this.price = price;
}

Enter fullscreen mode Exit fullscreen mode

Final flow:

Object Creation
       ↓
Default Values
       ↓
Field Initializers
       ↓
Constructor Execution

Enter fullscreen mode Exit fullscreen mode

This order is extremely important for understanding how Java objects are initialized.

10.Final Takeaway

A constructor is not just a special method—it is the starting point of an object's life cycle.

Whenever an object is created:

  1. Memory is allocated.

  2. Default values are assigned.

  3. Field initializers run.

  4. The constructor executes.

  5. The object becomes ready for use.

Understanding constructors also helps you understand other important concepts like this, object initialization, inheritance, and super() TBD.

If you're learning Java, mastering constructors is one of the best investments you can make before moving deeper into Object-Oriented Programming.