Oracle reference doesn't tell about best practice of this keyword while we overload constructors. Can anyone suggest the best practice for it?
public class A {
private int x, y, z, p;
public A() {
this(1,1,1,1);
}
public A(int x, int y, int z, int p) {
this.x = x;
this.y = y;
this.z = z;
this.p = p;
}
}
and
public class A {
private int x, y, z, p;
public A() {
this.x = 1;
this.y = 1;
this.z = 1;
this.p = 1;
}
public A(int x, int y, int z, int p) {
this.x = x;
this.y = y;
this.z = z;
this.p = p;
}
}
The first one is the best.
It is referenced multiple times in the offical docs and in many books. It is a specific case of method-chaining or, as others noted in the comments, telescoping constructors. They allows you to write less code and to not repeat yourself (DRY).
You can find that approach everywhere in solid libraries like Apache Commons and also in the best practices of other platforms. Finally, the famous book Thinking in Java, use this form in the Initialization & Cleanup chapter (Calling constructors from constructors section).