my dog learned polymorphism*
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing Private Static Variables" Watch "Accessing Private Static Variables" New topic

Accessing Private Static Variables

AnujS Sharma

Joined: Jul 30, 2011
Posts: 15

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.

Anuj Sharma
Matthew Brown

Joined: Apr 06, 2010
Posts: 4344

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

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.

Matthew Brown

Joined: Apr 06, 2010
Posts: 4344

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

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....

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 38107
Welcome to the Ranch

I would prefer to mark all fields private, except for "global" constants, and provide access as required via getXXX() methods.
subject: Accessing Private Static Variables
Similar Threads
Class instantiation within the same class
Jsp expecting Static reference to execute java function
Error message relating to Static variables
private static