Constructors and the new Keyword
In the previous lesson, you learned how to create an object using Car myCar = new Car();. But did you notice that every time we created a car or student, their fields were empty or had default values, forcing us to set each property manually:
Student s = new Student();s.name = "Aarav";s.age = 20;s.rollNumber = 101;What if a class has 15 fields? Writing 15 lines of assignments for every single object is exhausting and error-prone. Worse, what if someone creates an object and forgets to set the name or age? The program will have broken, half-initialized objects!
Java solves this fundamentally with Constructors.
1. What Is a Constructor?
A Constructor is a special method-like block of code that is invoked automatically at the exact moment an object is instantiated using the new keyword.
Its primary mission in life is: To initialize the object's initial state (give initial values to its fields) safely.
class Car { // Constructor definition Car() { System.out.println("🚗 A new Car object has just been born on the Heap!"); }}When you execute:
Car myCar = new Car();The output is immediate:
🚗 A new Car object has just been born on the Heap!
The Three Sacred Rules of Constructors:
- The name MUST match the Class name exactly (case-sensitive). If the class is
BankAccount, the constructor must beBankAccount(). - It has NO return type — not even
void! (If you putvoid Car(), Java treats it as an ordinary method, NOT a constructor!) - It cannot be called manually like normal methods — it is invoked strictly by the JVM during the
newinstantiation lifecycle.
2. The 3 Types of Constructors
| Constructor Type | Defined By | Parameters | Purpose |
|---|---|---|---|
| Default Constructor | Java Compiler (Automatic) | No parameters (no-arg) | Generated only if you write no constructors at all; sets fields to defaults (0, null). |
| No-Arg Constructor | You (The Developer) | No parameters | Explicitly provides custom default baseline values (e.g. balance = 100.0). |
| Parameterized Constructor | You (The Developer) | Accepts arguments | Forces callers to provide initial data when creating the object. |
3. The Default Constructor Rule (The #1 Beginner Trap ⚠️)
Beginners often ask: "Wait, in the previous lesson we wrote new Car() without defining any constructor in the class, and it still worked! Why?"
Because Java has a special rule:
If you write ZERO constructors in your class, the Java compiler (javac) automatically injects an invisible default no-arg constructor for you:
Car() { super(); // Calls Object class constructor}
The Trap: When does Java TAKE IT AWAY?
The moment you write even one custom constructor (such as a parameterized constructor), Java stops providing the automatic default constructor!
class Student { String name; // You defined a parameterized constructor: Student(String name) { this.name = name; }}public class Main { public static void main(String[] args) { // ✅ Works fine: Student s1 = new Student("Ananya"); // ❌ COMPILE ERROR! Student s2 = new Student(); }}Compiler Error:
The constructor Student() is undefined.
Why? Because you told Java: "I want students to be initialized with a name." Java respects that and removes its generic zero-parameter constructor. If you still want callers to create empty students with new Student(), you must explicitly write a no-arg constructor yourself!
4. Parameterized Constructors: Creating Ready-to-Use Objects
Instead of creating an empty shell and populating fields line-by-line, a parameterized constructor accepts arguments and initializes everything in a single, clean expression:
class Student { String name; int rollNumber; double gpa; // Parameterized constructor Student(String studentName, int studentRoll, double studentGpa) { name = studentName; rollNumber = studentRoll; gpa = studentGpa; }}Now, creating a student takes just one line:
Student s1 = new Student("Priya Sharma", 101, 3.85);Student s2 = new Student("Karan Patel", 102, 3.40);Both students are immediately valid, fully formed, and ready to use!
5. Variable Shadowing & The this Keyword
In real-world code, naming parameters studentName or n is considered poor practice. Good programmers name parameters after what they represent: name, rollNumber, gpa.
Watch what happens if we write this:
class Student { String name; // 1. Instance Field Student(String name) { // 2. Parameter name = name; // ❓ What happens here? }}If you do this, name = name assigns the parameter to itself! The instance field this.name remains untouched (null). This is called Variable Shadowing: a local parameter shadows an instance variable of the same name.
Enter this: "Me, Myself, and I" 🪞
Inside any class method or constructor, the keyword this is a reference to the current executing object on the Heap.
this.name = name;
─────────── ──────
│ │
Instance Field Incoming Parameter
(on the Heap) (on the Stack)
class Student { String name; int rollNumber; Student(String name, int rollNumber) { this.name = name; // Assigns parameter 'name' to the object's 'name' field this.rollNumber = rollNumber; // Assigns parameter 'rollNumber' to the object's field }}Real-World Analogy:
Imagine two people in a bank filling out a slip:
- Person A says: "My balance is ₹5,000."
- Person B says: "My balance is ₹12,000."
The word "My" adapts to whichever person is speaking. In Java, this refers to whichever specific object is currently being constructed or executing a method on the Heap.
6. Constructor Overloading: Multiple Ways to Build an Object
Just like you can order a pizza with:
- Standard default toppings
- 1 custom topping
- Build-your-own 5 toppings
A class can have multiple constructors with different parameter lists. This is called Constructor Overloading.
class Book { String title; String author; double price; // Constructor 1: Default / Unknown book Book() { this.title = "Untitled"; this.author = "Anonymous"; this.price = 0.0; } // Constructor 2: Title and author known, price not set Book(String title, String author) { this.title = title; this.author = author; this.price = 0.0; } // Constructor 3: Full details known Book(String title, String author, double price) { this.title = title; this.author = author; this.price = price; }}Now the client has complete flexibility:
Book b1 = new Book(); // Untitled by AnonymousBook b2 = new Book("Atomic Habits", "James Clear"); // Price 0.0Book b3 = new Book("Clean Code", "Robert C. Martin", 49.99); // Fully initialized7. Constructor Chaining with this() (DRY Principle)
Look closely at the overloaded constructors above. Did you notice repetitive code?this.title = title; is written multiple times!
In professional software development, we follow the DRY Principle (Don't Repeat Yourself). Java allows one constructor to call another constructor in the same class using this(...):
class Book { String title; String author; double price; // Master Constructor (does all the actual assignment) Book(String title, String author, double price) { this.title = title; this.author = author; this.price = price; } // 2-arg constructor: delegates to master constructor! Book(String title, String author) { this(title, author, 0.0); // Calls the 3-arg constructor } // No-arg constructor: delegates to master constructor! Book() { this("Untitled", "Anonymous", 0.0); // Calls the 3-arg constructor }}The Cardinal Rule of this() Chaining:
⚠️
this(...)MUST be the very first statement inside the constructor!
If you put any print statement or variable assignment beforethis(...), the Java compiler will immediately throw an error.
8. Complete Step-by-Step Runnable Program
Here is a comprehensive program demonstrating default values, overloaded constructors, and this() chaining:
// File: BankAccountDemo.javaclass BankAccount { String accountNumber; String accountHolder; double balance; // Master Constructor (3 parameters) BankAccount(String accountNumber, String accountHolder, double initialBalance) { this.accountNumber = accountNumber; this.accountHolder = accountHolder; this.balance = initialBalance; System.out.println("Created Account [" + accountNumber + "] for " + accountHolder); } // Overloaded Constructor: default initial balance of ₹500 BankAccount(String accountNumber, String accountHolder) { this(accountNumber, accountHolder, 500.0); // Delegates to master constructor } void deposit(double amount) { if (amount > 0) { this.balance += amount; System.out.println("Deposited ₹" + amount + ". New Balance: ₹" + this.balance); } } void displaySummary() { System.out.println("---------------------------------"); System.out.println("Account No : " + this.accountNumber); System.out.println("Holder : " + this.accountHolder); System.out.println("Balance : ₹" + this.balance); }}public class Main { public static void main(String[] args) { // Using the 2-arg constructor (defaults to ₹500) BankAccount acc1 = new BankAccount("SB-1001", "Meera Sen"); // Using the 3-arg constructor BankAccount acc2 = new BankAccount("SB-1002", "Vikram Rathore", 25000.0); acc1.deposit(1500.0); acc1.displaySummary(); acc2.displaySummary(); }}Console Output:
Created Account [SB-1001] for Meera Sen
Created Account [SB-1002] for Vikram Rathore
Deposited ₹1500.0. New Balance: ₹2000.0
---------------------------------
Account No : SB-1001
Holder : Meera Sen
Balance : ₹2000.0
---------------------------------
Account No : SB-1002
Holder : Vikram Rathore
Balance : ₹25000.0
9. Beginner Summary Checklist
- A Constructor is invoked automatically during
newto initialize fields. - Constructor names must exactly match the Class name and have no return type.
- Java provides an invisible default constructor only when you write zero constructors.
- As soon as you write a parameterized constructor, the default constructor disappears unless explicitly defined.
- The
thiskeyword refers to the current object executing on the Heap. this.field = field;resolves variable shadowing between instance fields and parameter names.- Constructor Overloading allows multiple ways to create an object with different parameter lists.
- Constructor Chaining with
this(...)reuses constructor logic and must be the first line of the constructor.