File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes a question about keyword static Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a question about keyword static" Watch "a question about keyword static" New topic

a question about keyword static

Tor Henning Post

Joined: Nov 14, 2003
Posts: 11
please excuse my english, i hope you will understand my question
I have a class InfoWindow that har a private static int counter.
and a method print that counts the counter up by one, and prensents a message in the InfoWindow
Then i have a class called Bank which extends thread, the constructor
creates an instance of InfoWindow. the run method checks if the bank is open and the calls the print method and lets the user know with 10 seconds interval. this is all good.
but then i made a Class Butikk (shop in english) and i did that by copy and paste, only replaced all bank statments with butikk. what suprised me was that the both the instance of Bank and butikk used the same counter if bank were 1 and butikk were 0 butikk would become 2 on its next count as long as bank were not counted up.
The constructor of InfoWindows is exactly the same in both Bank and Butikk
thus both instances are called iw (InfoWindow iw = new InfoWindow()) and i get two seperate wndows, so i would assume there were two instances of InfoWindow. isn't it? Do they then share the static counter? i would belive that since there are two instances each would have their own counter in a seperate memory location?

Scott Stoddard

Joined: Jan 30, 2004
Posts: 5
Well, you've mostly figured this out for yourself!
The term 'static' essentially means 'belongs to the class' instead of belongs to the instance.
Therefore, there is only ever one counter which will be initialized only once and incremented whenever print() is called (in your case).
If you wanted each instance to have its own counter, you should remove static.
I agree. Here's the link:
subject: a question about keyword static
It's not a secret anymore!