Overloading constructors should be thought of this way: it provides you with a way to construct the same object from different input sets. Here is an important rule about constructors:
When overloading a constructor, it is important that the parameters
passed to each constructor be sufficient to completely specify and
construct the target object (as required by its contract).
Calling a constructor always returns an object as long as there were no exceptions. You cannot invoke a second constructor on an object that has already been instantiated ... because it has already been constructed.
As an example, consider the following class:
public class Pair {
private final int x
private final int y
public Pair() {
this(0, 0);
}
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair(MyDoublet dbl) {
this.x = dbl.getX();
this.y = dbl.getY();
}
:
:
}
There are three constructors. Invoking any of them yields a completely specified Pair object. In fact, if a constructor didn't completely specify the Pair object the compiler would issue an error because, for the Pair class, all the instance fields are final and must be specified in the constructor.
Pair p1 = new Pair(); // p1 has x=0, y=0
Pair p2 = new Pair(1, 3); // p2 has x=1, y=3
Pair p3 = new Pair(0, 0); // p3 is the same has p1 even though a
// different constructor was used.
TLDR: Overloading constructors allows you to specify the construction of objects in the same class but with different sets of inputs.
"I want to know that whether I must initialize all the constructors in the class or it is okay not to call all of them."?? -- I'm not srue that I understand this statement as the user of the class would only call the most appropriate constructor, nothing more and nothing less. Please clarify.Dogs, then it is OK not to call anyDogconstructor. Is that what you are asking?Dogand never ever call it at all. Imagine that!public Doc() {this(20);}if your intention is to chain the constructors or re-use code