This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Understanding static reference to new object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding static reference to new object" Watch "Understanding static reference to new object" New topic
Author

Understanding static reference to new object

Mark O' Sullivan
Ranch Hand

Joined: Aug 17, 2009
Posts: 160
Hi,
I'm a bit confused about the use of the static keyword in the following case:
In 1 class I see this declared at the top of the class say called Data:

in constructor of same class:

What exactly does above do? I know the general stuff about:
(1) making a static reference to an object at start of class.
(2) making a static reference to a static method and initializing variables there.
I understand that is a static reference and only 1 copy exists for the class, but in the constructor is 1 creating a new object each time it's called for this static reference? Is there a point to this? Any help much appreciated as I find this confusing.
Thanks.

Francisco Montes
Ranch Hand

Joined: Sep 30, 2009
Posts: 30
What i see here is that the value of the static variable (for which, indeed, there is only one copy at class level) will always be changed everytime a new instance of that class is created.

Like you said, maybe it is not so useful to do something like that. Then again, maybe it is for that particular project. :-)

SCJP 1.6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37926
    
  22
It might be better to initialise a static variable like that in a static initializer block.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Campbell:

Agreed. I would also argue that the original code is an example of how not to use static variables.

John.
 
Don't get me started about those stupid light bulbs.
 
subject: Understanding static reference to new object
 
Similar Threads
SCJD Exam Book: Why is 'database' Static?
Questions about DvdFileAccess (code from the book)
SCJD Exam with J2SE book : DvdFileAccess Constructor
Errors in "SCJD Exam with J2SE 5" book
B&S: Making name and location data available to UI client