There are two types of methods.
Math
class. (See Math and java.util.Random).
From outside the defining class, an instance method is called by
prefixing it with an object, which is then passed as an implicit
parameter to the instance method, eg, inputTF.setText("");
A static method is called by prefixing it with a class name,
eg, Math.max(i,j);
.
Curiously, it can also be qualified with an object, which will be ignored,
but the class of the object will be used.
Here is a typical static method.
class MyUtils {
. . .
//================================================= mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements
for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
. . .
}
The only data this method uses or changes is from parameters (or local variables of course).
static
The above mean()
method would work just as well if
it wasn't declared static
, as long as it was called from
within the same class.
If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with
an object. Even when used within the class, there are
good reasons to define a method as static when it could be.
static
method can't interact
with instance variables, which makes reading and
debugging easier.
There are two cases.
// Called from inside the MyUtils class double avgAtt = mean(attendance);
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be
ignored and the the class of the object will be used.
Altho a static
method can't access instance variables,
it can access static
variables. A common use of
static
variables is to define "constants".
Examples from the Java library are Math.PI
or
Color.RED
. They are qualified with the class name,
so you know they are static
.
Any method, static
or not, can access static variables.
Instance variables can be accessed only by instance methods.
What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.