my dog learned polymorphism*
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 OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a question about keyword static" Watch "a question about keyword static" New topic
Author

a question about keyword static

Tor Henning Post
Greenhorn

Joined: Nov 14, 2003
Posts: 11
Hello
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
Greenhorn

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.
Scott
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a question about keyword static