Anil Philip wrote:If the first line is a call to another ctor, then how can you set a field on that line also?
you can only transform the data on the first line. After the first line, all of the fields will already be assigned
That call to the other constructor is
how the fields are being set. Running the other constructor sets the fields.
But while the first line must be a call to another constructor, there are nonetheless ways to insert some transformation of the data before the constructor is called. You show one yourself:
Here the first line of the Crane(int,
String) constructor is an invocation of the canonical constructor - and yet, it
is changing the data on the way. It's replacing numberEggs with numberEggs + 1. And it's putting firstName and lastName together into a single name, separated by " ". Those are both transformations of data, made by inserting simple expressions into the constructor invocation. You could also insert an arbitrarily complex expression into that first line - but at some point, it's better to create a new static method, and insert that instead:
So you can squeeze quite a bit of transformation into that one line, if you need to. Note that you aren't allowed to invoke an instance method there, or a this reference, because the current instance isn't fully constructed yet. But you can do a lot of other things with the constructor parameters.
Anil Philip wrote:Then you might as well have just one compact constructor!
A compact constructor is a more flexible way to handle this sort of initialization. But you can only have one compact constructor, and it is a direct companion to the one canonical constructor - that is, you can only reference variables from the canonical constructor arguments, and the canonical constructor is implicitly called at the end of the compact constructor. The point being, all of this is of no help if you want to be able to create a constructor with a different list of arguments. For that you need an overloaded constructor, by definition. And that's when you have to deal with the no-data-alteration-except-on-first-line rule.
Note that they are finding ways to relax these rules in future versions of
Java, starting with JDK 22. But for now, these are the rules we must deal with.