Memra

Constructor overloading & this()

Multiple constructors, chaining with this(), and disambiguating fields.

Multiple constructors

Constructors can be overloaded just like methods:

public class Point {
    int x, y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    Point() {
        this(0, 0);  // delegate to the two-arg constructor
    }
}

this(...) constructor chaining: one constructor calls another of the same class. This prevents copy-pasting initialisation logic. Rules: - this(...) must be the first statement in the constructor body — anything before it is a compile error. - You cannot chain to yourself (no cycles allowed). - Contrast with super(...), which chains to a parent-class constructor.

this.field (with a dot) distinguishes an instance field from a same-named parameter:

void setName(String name) {
    this.name = name;  // this.name = the field; name = the parameter
}

Without this., both name references would resolve to the parameter and the field assignment would do nothing.

NORMAL ~/memra/learn/java-from-zero/constructor-chaining utf-8 LF