posted 17 years ago
This comes up all the time:-
A static method belongs to the class, not to any perticular object. (Also a static field, so I shall say "static member.")[list]To call a static member bah from a class Foo you say Foo.bah or Foo.bah() rather thanThere is only one of each static member in memory, whereas there is one object field for each instance, so there may be many different instance fields in memory.Each object of the class has access to all its static members, but not vice versa. You cannot call an instance member from inside a static method, nor can you use the this keyword (and I think you can't use the super keyword in a statiuc method either).Each instance has access to every static member, and it is always the same copy for all instances. So a change made to a static field by "myFoo.baah(234);" will change the static field for every other instance; it will have the same value if you call bah from myFoo.baaah(), yourFoo.baaah() or ourFoo.baaah().
When would you use a static method?
When you pass information and want an answer which does not affect the other fields. Example: the Math class has a sin() method. You pass a number and it works out the sine of that number (in radians). It doesn't affect any fields of the Math class. So it is declared as a static method. [In fact every public member of the Math class is static.]When you want a field which is the same for every instance of the class. Example: you have a MyLinkedElement class which forms part of a MyLinkedList. Your add() method includes "count++;" and your remove() method includes "count--;"
The "count" field is a static field, which counts how many elements there are in the LinkedList. You have a public static getCount() method, and saying "MyLinkedElement.getCount()" tells you how many elements you have.[edit]Nearly forgot:
Another use of static members is for "constants." If you have a constant, it will be the same always and the same for every member of the class. Many people declare such constants like this:-[/edit]
CR
[ August 25, 2006: Message edited by: Campbell Ritchie ]