Static Methods
Every method must be in a class
A static method is not invoked on an object
Why write a
method that does not operate on an object?
Common reason: encapsulate some computation that involves
only numbers. Numbers aren't objects, you can't invoke
methods on them. E.g.,
x.sqrt()
can never be legal in Java
public class Financial
{
public static double percentOf(double p, double a)
{
return (p / 100) * a;
}
// More financial methods can be added here.
}
Call with class name instead of object:
double tax = Financial.percentOf(taxRate, total);
main is static – there aren't any objects yet
Suppose Java had
no static methods. Then all methods of the
Math
class would be instance methods.
How would you compute the square root of
x?
Answer:
Math m = new Math();
y = m.sqrt(x);