GeeCON Prague 2014*
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


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: 4397
    
    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: 4397
    
    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: 39072
    
  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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing Private Static Variables