Course contentsShow
← Java
Lesson 321 of 2,8708. Classes and EncapsulationFree lesson

Calling Another Constructor with this()

Understand how 'this()' invokes another constructor in the same class to avoid code duplication, reducing initialization logic.

Calling Another Constructor with this()

You'll learn how to call one constructor from another in the same class to avoid repeating initialization code.

The Core Idea

When you have multiple constructors in a class (constructor overloading), you often find yourself writing the same initialization logic over and over. Java provides a special syntax—this()—that lets one constructor call another constructor in the same class. This keeps your code DRY (Don't Repeat Yourself) and ensures all objects are initialized consistently.

Think of it like a restaurant with different order forms: a "full order" form and a "quick order" form with defaults. Instead of the chef reading both forms independently, the quick form just says "fill in the missing items with our standards, then read the full form." That's what this() does—it delegates to another constructor.

How It Works

public class Book {
    private String title;
    private String author;
    private int pages;

    // Full constructor
    public Book(String title, String author, int pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    // Simpler constructor calls the full one
    public Book(String title, String author) {
        this(title, author, 0);  // Calls the 3-parameter constructor
    }

    // Even simpler constructor
    public Book(String title) {
        this(title, "Unknown");  // Calls the 2-parameter constructor
    }
}

Important rule: this() must be the first statement in the constructor. You cannot put any other code before it.

This technique eliminates duplicate initialization logic and creates a single "master" constructor where all the real work happens.

Key Takeaway:
Use this() as the first line in a constructor to invoke another constructor in the same class, centralizing initialization logic and avoiding code duplication.