Static methods in Java are equivalent to top-level (un-nested) procedures in Scheme, Pascal, or C. There is absolutely no conceptual difference between defining a static method in Java and a top level procedure in Scheme, Pascal, or C. However, the appropriate usage of static methods in Java is very limited. With a very few exceptions discussed later in the monograph, static methods should only be used to define operations where all of the inputs to the operation are primitive values.
If you are acquainted with C syntax, then the syntax for a Java static method definition will be familiar; except for minor differences in the definition header, the Java syntax is nearly identical.
To illustrate the definition of static methods, let us examine the the
simple problem of converting the measurement of a person's height from
inches to meters. To solve this simple ``word problem'', all we have
to write is a static method to convert inches to meters. Since 1
meter = 39.37 inches, the formula for converting i inches to
m meters is:
The definition of the method inToM consists of two parts:class Conversions { static double inchesPerMeter = 39.37; static double inToM(double i) { return i/inchesPerMeter; } }
static double inToM(double i)stating that inToM is a static method that returns a result of type double and takes a single input parameter i of type double. In Java, the type of every method parameter must be declared.
{ return i/inchesPerMeter; }of the method consisting of a sequence of statements enclosed in parentheses specifying what value the method returns.
To convert a height of 70 inches to meters using DrJava, all that you have to do is evaluate the expression
Conversions.inToM(70)Interactions window. Note that you must qualify the static method name inToM by the prefix
Conversions.to indicate which class contains the inToM method. Within the body of the Conversions class, this prefix is unnecessary. Any static method name without a prefix is assumed to be in the current class.
Finger Exercise: enter the class Conversions in the DrJava Definitions window, compile it, and evaluate several invocations of
the static method inToM.