aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why dont... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why dont..." Watch "why dont..." New topic
Author

why dont...

O Joseph
Ranch Hand

Joined: Jun 27, 2003
Posts: 75
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.


XX.
Jeff Bosch
Ranch Hand

Joined: Jul 30, 2003
Posts: 804
Are you asking a question?


Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
O Joseph
Ranch Hand

Joined: Jun 27, 2003
Posts: 75
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

Joined: Jul 30, 2003
Posts: 804
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

Joined: Jun 27, 2003
Posts: 75
thanks meen,
should ve known . guess i'm a bit fatigued. havent slept for ages.
about ur curiosity, i'll mail u soon.
cheers.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why dont...
 
Similar Threads
question about static variable...
Need Explanation of unpredicted output even if methods are synchronized
Importing java files in another java program
Post increment operator
about static variable question