Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing Private Static Variables

 
AnujS Sharma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4567
8
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True. And it's possible they were the ones making the mistake, and not you .
 
Somashekhar Dhanashree
Greenhorn
Posts: 1
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Sheriff
Pie
Posts: 48967
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I would prefer to mark all fields private, except for "global" constants, and provide access as required via getXXX() methods.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic