This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Accessing Private Static Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing Private Static Variables" Watch "Accessing Private Static Variables" New topic
Author

Accessing Private Static Variables

AnujS Sharma
Greenhorn

Joined: Jul 30, 2011
Posts: 15
Hi,



In the main class,



Now, I am getting an error on the line 'usingStatic.counter' becuase it has been declared as a private variable. If it is declared as public or protected, the code compiles fine.

The reason why I am not assuming this and asking you guys is that in one of the tutorials on the internet, they complied the same code i.e. they were able to access the private static variable.

Am I doing something wrong here or you actually cannot access the private static variable.



Thanks,
Anuj Sharma
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4376
    
    8

You can't access a private variable (static or otherwise) from another class. If you saw something similar in a tutorial, then the chances are it was actually accessing it from the same class. For instance, if you move the main() method to the usingStatic class, then it will work.

(Oh, and do call it UsingStatic rather than usingStatic, won't you? Life is much easier if you follow the standard conventions.)
AnujS Sharma
Greenhorn

Joined: Jul 30, 2011
Posts: 15
I am pretty sure that the static variable was being called from another class, but maybe I am wrong.

To err is to human.

Thanks.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4376
    
    8

True. And it's possible they were the ones making the mistake, and not you .
Somashekhar Dhanashree
Greenhorn

Joined: Feb 03, 2011
Posts: 1


1. Visible to the package. the default. No modifiers are needed.

2. Visible to the class only (private).

3. Visible to the world (public).

4. Visible to the package and all subclasses (protected).

You can use protected instead....


Thanks/Regards
$oM
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38517
    
  23
Welcome to the Ranch

I would prefer to mark all fields private, except for "global" constants, and provide access as required via getXXX() methods.
 
Don't get me started about those stupid light bulbs.
 
subject: Accessing Private Static Variables