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

this() Must Be the First Statement

Learn the critical rule that 'this()' must appear as the very first statement in a constructor body.

this() Must Be the First Statement

You'll learn why Java requires this() to appear as the very first line when calling another constructor.


In the previous lesson, you learned that you can call one constructor from another using this() to avoid duplicating initialization code. But there's a strict rule: this() must be the very first statement in the constructor body—before any other code, assignments, or method calls.

Why This Rule Exists

When you call this(), Java needs to ensure the object is properly initialized before any other code runs. Think of it like building a house: you must pour the foundation (complete the primary constructor) before you can paint the walls (execute additional statements). Java enforces this order to guarantee the object is in a valid state from the start.

What Happens If You Break the Rule

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person(String name) {
        System.out.println("Creating person..."); // ERROR!
        this(name, 18); // Compiler error: this() must be first
    }
}

The compiler will reject this code. You cannot execute anything—not even a print statement—before this().

The Correct Way

public Person(String name) {
    this(name, 18); // Must be first!
    System.out.println("Person created"); // Now this is allowed
}

Once the this() call completes (and the other constructor finishes), then any remaining statements in your constructor will execute.


Key Takeaway: When using this() to call another constructor, it must be the absolute first statement in the constructor body—Java enforces this to guarantee proper object initialization order.