Krithika Sundaram wrote:Can anyone please explain me the need for static methods and 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.
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!