• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

private static int x

 
mayur dhawan
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I want to know what is the benefit of using private static declaration like this.
and How are we going to use this declaration.

thanks
mayur
 
Antonio Tercero
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A static variable can be accessed from a static or non-static method.
Example:
 
Taariq San
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by mayur dhawan:
Hi,
I want to know what is the benefit of using private static declaration like this.
and How are we going to use this declaration.

thanks
mayur



One benefit might be that all instances of your class share that variable, one makes a change that all of them see.
I've modified Antonio's example to illustrate this.



1 common use is counters, say everytime a constructor is called, so you always know how many instances there are. That sort of thing.

That's just the static part, the private modifier is to restrict access to it's own class.
 
Antonio Tercero
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Taariq is right.
static variables and methods belong to the class, so if you want to access a static variable or call a static method from another class, you can do that(recommended):



Remember that static variables and methods are shared among all objects of the class.
 
Ben Zaidi
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Important benefit in additions to described above, you can access a
static variable, even if there are no instances of class created, by
simply invoking it through the class name. Static members are class
level variable rather then instance level.

Hope this helps,

Ben
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic