Re: When would you declare a method as static?
On 03/27/2011 05:23 PM, Merciadri Luca wrote:
I read on various websites that a method is generally declared as
static if it `achieves some computations.' Well, this is fairly vague,
Those are bad sources.
All methods "achieve some computations".
and I would have the tendency to declare a method as static if it
produces the same result for every instance of the class (that is,
that it produces some variable that might be declared as static).
Any help would be greatly appreciated.
A static member is one that belongs to the entire class. An instance member
is one that belongs to an instance. A method is a member. A static method
belongs to the entire class. It cannot directly refer to instance members
because it is not tied to an instance.
package example;
public class Example
{
public static void useful( Example ex )
{
foo.run(); // ILLEGAL! tried to use an instance member
instant(); // ILLEGAL! tried to use an instance member
ex.foo.run(); // LEGAL! accessed through an instance
ex.instant(); // LEGAL! accessed through an instance
}
/* p-p */ final Foo foo = new Foo(); // assume a run method
public void instant()
{
}
}
The "produces the same result" rule of thumb will not work. A static method
can produce all kinds of results. The rule of thumb is whether it needs state
specific to an instance. If not it can be static.
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg