Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private static

 
Vinney Shanmugam
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can a instance variable be declared as private static? It's possbile, but once you declare a variable as static, it's no more a instance variable, so I am not getting the ratinale behind it.

Also, What is the use of such a variable, real use case will help me to understand it easily.
 
Steve Luke
Bartender
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinney Shanmugam wrote:can a instance variable be declared as private static?
No. An instance variable is a non-static variable (and conversely a static variable is not an instance variable) so you can not have a 'static' instance variable of any visibility.

It's possbile, but once you declare a variable as static, it's no more a instance variable, so I am not getting the ratinale behind it.
You can have a private static variable, yes. This means the variable would be statically available to the class it is declared in. All instances of the class would share the same value, but no other classes could access it.

Also, What is the use of such a variable, real use case will help me to understand it easily.
The first thing to come to mind would be an 'instance counter'. Let's say we have a Widget, and we want all Widgets created in the app to have an ID. We could use a running count of Widgets to make sure each one gets an ID:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic