Junilu Lacar wrote:
After looking over that section and reading this paragraph several times, my opinion is that this is a poorly constructed/edited paragraph with a few disparate thoughts running into each other incoherently. The first sentence refers to line 22, the print statement that causes the output of "Inside Bath()". The rest of the paragraph is just an incoherent, confusing, and long run-on sentence. The code example it refers to demonstrates the four ways he listed that an object reference can be initialized. Only the first way, initializing at the point of definition, guarantees that the reference will be non-null (unless you explicitly initialize it to null, of course).
Primitives that are fields in a class are automatically initialized to zero, as noted in the Everything Is an Object chapter. But the object references are initialized to null, and if you try to call methods for any of them, you’ll get an exception-a runtime error. Conveniently, you can still print a null reference without throwing an exception.
It makes sense that the compiler doesn’t just create a default object for every reference, because that would incur unnecessary overhead in many cases. If you want the references initialized, you can do it:
At the point the objects are defined. This means that they’ll always be initialized before the constructor is called.
In the constructor for that class.
Right before you actually need to use the object. This is often called lazy initialization. It can reduce overhead in situations where object creation is expensive and the object doesn’t need to be created every time.
Using instance initialization.
Note that in the Bath constructor, a statement is executed before any of the initializations take place. When you don’t initialize at the point of definition, there’s still no guarantee that you’ll perform any initialization before you send a message to an object reference—except for the inevitable run-time exception.
When toString( ) is called it fills in s4 so that all the fields are properly initialized by the time they are used.