| Author |
Need for static methods and variables
|
Krithika Sundaram
Greenhorn
Joined: Oct 16, 2009
Posts: 4
|
|
Can anyone please explain me the need for static methods and variables?
Thanks,
Krithika
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3327
|
|
Welcome to JavaRanch, Krithika Sundaram
|
Everything has got its own deadline including one's EGO!
[CodeBarn] [Java Concepts-easily] [Corey's articles] [SCJP-SUN] [Servlet Examples] [Java Beginners FAQ] [Sun-Java Tutorials] [Java Coding Guidelines]
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3327
|
|
Krithika Sundaram wrote:Can anyone please explain me the need for static methods and variables?
Static Variables
When we want a variable to be shared across all instances of a class, we need a global variable. Static variables are of rescue here. Otherwise, all the variables will be specific to a particular instance (object) of the class.
One good example : If you want to count the # of instances being created for a particular class. Where will you have such variable/count? It should be outside the object scope and that is nothing but the class level scope -- static variable.
Static Methods
There are cases when we have methods doing some activity NOT specific to an instance of a class but in general. Say for example, if you want to print a message based on the person's age, you can have it as an instance method for example, isEligible() which says whether the person is eligible or not based on his age. If you look at this, 'age' is a specific property of each object. So this method has to be an instance method.
whereas, if you look at the method named getSystemDate() that does NOT need to print anything based on the object's state/data. Hence it is common to all objects and does NOT need any instance to invoke it. -- Class level or static method it is called as.
Guess this helps
You can read sun's online tutorial for more!
|
 |
Rok Ć telcer
Ranch Hand
Joined: Nov 03, 2009
Posts: 101
|
|
You can read sun's online tutorial for more!
And here is the link:
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
Regards,
Rok
|
SCJP, SCWCD
|
 |
Krithika Sundaram
Greenhorn
Joined: Oct 16, 2009
Posts: 4
|
|
Raghavan Muthu wrote:Welcome to JavaRanch, Krithika Sundaram
Thanks Raghavan!
|
 |
Krithika Sundaram
Greenhorn
Joined: Oct 16, 2009
Posts: 4
|
|
It was very helpful. I appreciate your elaborate response. Thanks to Raghavan and Rok.
|
 |
Raghavan Muthu
Ranch Hand
Joined: Apr 20, 2006
Posts: 3327
|
|
You are welcome Krithika and it is our pleasure
|
 |
 |
|
|
subject: Need for static methods and variables
|
|
|