• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static member is not initialized again when creating an object for the second time. Why?  RSS feed

 
Laimonas Oberauskis
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

here is the code:



The answer is "tacfacb".

Why does the "value" not get initialized anew after new Test() is called?
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what static means.  A static initializer "belongs" to the class, not any one object, and gets executed when the program starts, I believe.  
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The static initialiser runs once, as you said, Liutauras, when the class is first loaded into memory.
That is why we used to write Class.forName() when opening database connections. The database connectivity class had a static initialiser which made the connection, and that runs when the class is first loaded. If Class.forName() doesn't cause it to run, that is because the class has already been loaded once and the static initialiser has already been executed.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!