Friday, March 18, 2011

What is a static member in Java? - OOD 101

The keyword 'static' preceding a variable(field) or a method makes its static.

static means, one per class and not one for each instance of the class (or object). This means that you can use them without creating an instance of a class.

Static variables (class variables) VS Instance variables:
When a number of objects are created from a class, each object gets gets its own copy of the instance variables.
Static variables are however associated with the class, rather than with any object of the class. Every instance of the class shares the same class variable, which is in one fixed location in memory. The class variable can be accessed without creating an instance of the class and any object can change the value of a class variable.

Static  methods (class methods) VS Instance methods:
Instance methods are associated with an object and use the instance variables of that object.
Static methods use no instance variables of any object of the class they are defined in. A Static method can only access static variables and cannot access the instance variables. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class.

No comments:

Post a Comment