Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why dont...

 
O Joseph
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.public class ConnectionPool {
2. public static int connectionCounter = 0;
3. public ConnectionPool() {
4. increment();
5. }
6. private void increment() {
7. connectionCounter++;/* WHY NO COMPILER ERROR HERE; AFTERALL connectionCounter is static and increment() is not? */
8. }
9. public static void main(String[] args) {
10. ConnectionPool cp = new ConnectionPool();
11. cp.connectionCounter = 0;
12. ConnectionPool pool = new ConnectionPool();
13. System.out.println (cp.connectionCounter + " " +
14. pool.connectionCounter);
15. }
16.}

Answer reads 1,1.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you asking a question?
 
O Joseph
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, if moi english aint so clear, i aint an english mon u know.
moi question is on line 7 and it is based on the fact that a static
variable cant be accessed in a non-static context?
am i clear?
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay, now I see the question. Sorry for the confusion.
You can access a static variable from a nonstatic context, but not the other way around.
Here, when you increment the variable, you're incrementing it for all instances of the class. In other words, a static variable gives you one copy that all instances share, whereas a nonstatic variable (aka instance variable) gives you one copy per instance.
Hope that helps.
By the way, where are you from? What's your programming/Java background?
Also, your code snippets would be much easier to read if you used the UBB Codes for formatting.
Thanks.
 
O Joseph
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks meen,
should ve known . guess i'm a bit fatigued. havent slept for ages.
about ur curiosity, i'll mail u soon.
cheers.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic