I read why it's needed (please see excerpt below) but I'm still not clear on its purpose? Any additional details that you can provide would be greatly appreciated. Thanks.
Why do we need constructor chaining ?
This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable.
I can think of three broad categories in which constructor chaining falls.
Calling 'general case' constructors from 'specific case' constructors.
Calling 'basic' constructors from 'extending' constructors.
Calling superclass constructors from subclass constructors.
The reason for calling superclass constructors should be obvious: When you extend a class, you want to be able to initialize the fields of the superclass when you create an instance of the subclass. I won't delve into this topic further unless you specifically ask me about it.
By 'general case' constructor I mean a constructor that lets you specify all the information to initialize an object with explicitly. A 'specific case' constructor calls it with sensible default values for common use cases:
Calling 'basic' constructors from 'extending' constructors is a bit of the mirror opposite of calling 'general case' constructors from 'specific case' constructors. The basic constructor initializes the object to the most basic valid initial state, and extending constructors modify the initial state for other use cases:
As you can see, each additional extending constructor first calls a more basic constructor and then performs additional tasks. This is what the the paragraph you quoted refers to. I'm not a fan of this approach, because usually the same can be achieved by just calling the basic constructor, and then calling methods on the initialized object to modify its state. It's also less efficient that the 'general case'/'specific case' way of chaining constructors, because fields are initialized to values that are then possibly overwritten in an extending constructor.
As a final remark, instead of supplying 'specific case' constructors, you can also use factory methods which often make the class even nicer to use. So instead ofwe do
posted 1 week ago
Thanks for the time, effort, and thought you placed in this response.
I will have to read this a couple more times.
If I remember correctly, Factory method is a Design Pattern? Anyways, thanks and I will absorb all this fabulous information.
Is this something that is used often?
Again, thanks for the input!
Bring me the box labeled "thinking cap" ... and then read this tiny ad: