• 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
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

timing of the constructor running

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The code below is a variation of a question from the B & S book.



produces:

One3()
assert
Exception in thread "main" java.lang.AssertionError
at p1.One2.<init>(Two.java:9)
at p1.Two.main(Two.java:13)


x is not static.

The initialization block runs before the instance of One2 is created. How could x exist at the time the assert is evaluated?

Thanks.

Matt

 
author
Posts: 23893
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

matt love wrote:The code below is a variation of a question from the B & S book.



produces:

One3()
assert
Exception in thread "main" java.lang.AssertionError
at p1.One2.<init>(Two.java:9)
at p1.Two.main(Two.java:13)


x is not static.

The initialization block runs before the instance of One2 is created. How could x exist at the time the assert is evaluated?

Thanks.

Matt




All instance variables are actually available during construction -- and you have the responsibility to make sure that you use it correctly. In this case, it looks fine. Initialization of instance variables, along with initialization blocks, are done in the order that they are encountered in source code, so the init block is executed after the variable have been set to zero.

And BTW, if you happen to use it before it has been initialized, the variable will have the default value -- which for primitive ints, is a value of zero.

Henry

 
matt love
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry.

Matt
 
I don't like that guy. The tiny ad agrees with me.
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic