• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is static  RSS feed

 
Nikos kat
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've found this subject very hard to understand. Can anyone explain it to me it is in simple terms. I just don't see when to use a static variable.
 
karthikeyan Chockalingam
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
static variable is one not that is not appropriate when related to an instance of a class (that is object). Hence instead of having it specific to each object it is made specific to a class.

Consider the following requirement.
A company has x number of employees. Currently pine apple juice is served free during intervals. There is a poll to decide if the employees favour water melon as summer has started. Let us consider the below implementation without using static variables.


Here whenever an employee votes you invoke the vote() method. Finally you get all Employee objects and iterate through them to find the total number of employees who have favoured water melon (if hasVoted() returns true increment the count by value 1)

The overhead is x number of employee object instances have to be created. Now let us look at the usage of static variable to count the votes.



When each employee votes vote() method is invoked and finally just invoke
getNumberOfVotes() to get the count. Here the overhead of creating x number of Employee objects is eliminated.
 
Nikos kat
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much, thats helped a lot
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Nikos k,"

Welcome to JavaRanch!

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names, with a first and a last name.

You can edit your name here.

Thank you for your prompt attention, and enjoy the ranch!

-Marc
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!