Constructor Chaining with this()
You'll learn how to call one constructor from another within the same class to avoid duplicating initialization logic.
The Core Idea
When you have multiple constructors in a class, you often find that they share common initialization code. Instead of repeating that logic in each constructor, Java lets you chain constructors together using this(). One constructor can call another constructor in the same class, allowing you to build more complex initialization on top of simpler versions.
The Critical Rule: First Statement Only
When you use this() to call another constructor, it must be the very first statement in your constructor body. You cannot execute any other code before the this() call—not even a simple variable assignment or print statement.
public class Product {
private String name;
private double price;
private int quantity;
// Primary constructor with all parameters
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
// Chains to the primary constructor, defaulting quantity to 0
public Product(String name, double price) {
this(name, price, 0); // MUST be first statement
}
// Chains to the two-parameter version, defaulting price to 0.0
public Product(String name) {
this(name, 0.0); // MUST be first statement
}
}
Think of It Like Delegating Setup
Imagine building a sandwich. Your "deluxe constructor" adds everything. Your "basic constructor" can say "start with the deluxe version, but use these default ingredients." You're delegating the actual assembly work to avoid repeating the recipe.
Key Takeaway:
Use this() as the first statement in a constructor to call another constructor in the same class, eliminating duplicate initialization code through constructor chaining.