Win a copy of Kotlin Cookbook this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Joe Ess
  • salvin francis

Whould you explain sentences from the book "Thinking in Java"

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello.
Can someone explain me this sentences from the book "Thinking in Java Bruce Eckel 4th ed."
Page 167. In section with explaining "Composition syntax"

What mean "Note that in the Bath constructor, a statement is executed before any of the initializations take place."?
Can you also explain phrase "before you send a message to an object reference"?

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:
1.
At the point the objects are defined. This means that they’ll always be initialized before the constructor is called.
2.
In the constructor for that class.
3.
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.
4.
Using instance initialization.



All four approaches are shown here:


Explanation from book.

   

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.




 
Marshal
Posts: 67036
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Careful when copying code like that; you have managed to include the page numbers!

A long time ago, Gosling &Co designed the language so all non‑final fields are given default values: as Eckel said, 0/0.0/false for primitives and null for reference types. There should be something in the JLS (=Java® Language Specification), but I can't seem to find it. If you don't initialise those fields somewhere, they will retain their default values, except if they are final fields, which must be initialised before the constructor completes.

More to follow: watch this space.
 
Campbell Ritchie
Marshal
Posts: 67036
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is potentially dangerous to leave the default values. The invariants of the class might forbid a value of 0. A null left lying around can cause an exception if you try to use it. So you might cosider lazy initialisation:-I can see problems with that approach:-
  • 1: The amount of memory and time saved by not initialising that field early is slight. That may eventually be overwhelmed by the additional work in that test if the getXyz() method is called frequently.
  • 2: That sort of method isn't thread‑safe. It is possible for that method to be called in two threads and you won't know which XYZ object is actually created.
  • 3: It is awkward to pass information to that XYZ object's constructor.
  • 4: It is difficult to be certain that xyz has been initialised before it is used, and use null unexpectedly.
  • You can initialise a field alongside its declaration; the following line is called a declaration with initialisation:-Not sure, but I think that initialisation is done before the constructor. As I said, not certain. You can use an initialliser, which looks like a mysterious block just standing around the class, propping up the bar, or hiding in the corners where you would hardly notice it:-It doesn't matter whether you write the initialiser before or after the declaration. If you have multiple initialisers, they run in the order they are written in. The instance initialisers run after the superclass' constructor (or super(...);) and before any of the other code in this class' constructor.

    Both those approaches ensuree the field will be initialised to a realistic value (=establishing the class' invariants). But it is awkward to pass any information so different objects can have different states to their fields.

    You have doubtless seen constructors before:-That has the disadvantage that you have to write a constructor, but surely you aren't going to write any classes without constructors. It also have the advantage that it is very straightforward to pass information from other code. It may therefore be necessary to validate the information passed before you accept the constructor argument. This might be the simplest kind of validation; I shall let you look up the link to see what it does:- this.xyz = Objects.requireNonNull(xyz);
     
    Ranch Hand
    Posts: 85
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Sergey -

    What mean "Note that in the Bath constructor, a statement is executed before any of the initializations take place."?
    Can you explain also explain phrase "before you send a message to an object reference"?

    If I am understanding your question, when you create an Object, a Constructor is called.  I think it's saying that some code is ran inside the compiler prior to the Constructor being called.  If you don't have a Constructor defined then the system will use the 'default' one.

    In Object-oriented Programming (OOP), a program is a bunch of Objects communicating with each other (paraphrased from the book).  With that in mind, your Methods 'communicate' with other Objects.  So, the message in this context, I believe, is any 'Call' made to an Object reference (and not the actual Object itself).  I hope this helps.

    I'm pretty new at this but these are me thoughts....I'm reading the same book but I'm not as far as you.
     
    Sheriff
    Posts: 14620
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    "sending a message to an object reference" is another way of saying "calling a method." That is, given a String reference, str, then str.toString() can be referred to as "calling the toString() method of the str object" or "sending the toString() message to the str object."

    This terminology ("sending messages to objects") is not commonly used when talking about Java but in other OO languages, like Smalltalk, it apparently is.  See "sending messages to objects"  and http://esug.org/data/Old/ibm/tutorial/CHAP2.HTML#2.00
     
    Junilu Lacar
    Sheriff
    Posts: 14620
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    It seems to me that "in the Bath constructor, a statement is executed..." refers to the print("Inside Bath()") statement (line 22). I'm not sure how that relates to what he's trying to explain in that section of the book though.
     
    Junilu Lacar
    Sheriff
    Posts: 14620
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sergey Smachek wrote:Explanation from book.

    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.


    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).

    Refer to this code instead:

    Go to https://repl.it/repls/ConsciousDualRedundancy if you want to run the above code. This is the output:

    If uncommented, line 10 will cause a compile-time error. I included this because it shows that the compiler actively guards against accessing uninitialized values.

    Lines 13-15 show another initialization block. This shows that object references like s are set to null by default. I think one of the problems with the book section in question that makes it confusing is that the word "initialized" is mainly used to mean "set to a non-null value" except for that one part where he writes "But the object references are initialized to null".

    The output shows that initialization blocks are executed before any code in a constructor is executed (because the last line in the output is "blah", not "bar")
     
    Campbell Ritchie
    Marshal
    Posts: 67036
    255
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Sergey Smachek wrote:. . . "Thinking in Java Bruce Eckel 4th ed." Page 167.  . . .

    Please check carefully; I can't find anything like that on page 167 in my copy.
     
    Junilu Lacar
    Sheriff
    Posts: 14620
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Campbell Ritchie wrote:

    Sergey Smachek wrote:. . . "Thinking in Java Bruce Eckel 4th ed." Page 167.  . . .

    Please check carefully; I can't find anything like that on page 167 in my copy.


    167 is the page number that's at the bottom of the "printed" page, not the page number according to Acrobat Reader's navigation control (pg 189).
     
    Rancher
    Posts: 3412
    34
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Seems like there's more than one version of "4th ed" out there.  The free online version of TiJ 4th ed R1 (Revision 1?) has this on "printed" page 236-7, "reader" page 265-6.  See here.
     
    Junilu Lacar
    Sheriff
    Posts: 14620
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    The one I'm referencing is also a free download, Dec 2007.
     
    Campbell Ritchie
    Marshal
    Posts: 67036
    255
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you. I didn't know there were any free downloads after the 3rd edition; I only have the paper version of the 4th edition, which I got about June 2006.
     
    Sergey Smachek
    Greenhorn
    Posts: 4
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    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).



    Thank you for answer and excellent explanation!
    I had my suspicions that this was an inaccurate description in the book. But I doubted it, because I don't speak enough English.
     
    To avoid criticism do nothing, say nothing, be nothing. -Elbert Hubbard. Please critique this tiny ad:
    Sauce Labs - World's Largest Continuous Testing Cloud for Websites and Mobile Apps
    https://coderanch.com/t/722574/Sauce-Labs-World-Largest-Continuous
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!