next up previous
Next: 1.2.9 Capitalization and Commenting Up: 1.2 Java Mechanics Previous: 1.2.7.2 Variations on the

  
1.2.8 Defining Static Methods

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:

\begin{displaymath}\frac{1}{39.37} = \frac{m}{i}
\end{displaymath}

which is equivalent (via cross-multiplication) to

39.37*m = 1*i

Hence,

m = i/39.37

The method inToM(double i) in the following class computes m given i:
class Conversions {
  static double inchesPerMeter = 39.37;	
  static double inToM(double i) { return i/inchesPerMeter; }
}
The definition of the method inToM consists of two parts: The data type double is the default form of floating-point arithmetic in Java, just as it is in Scheme.

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.


next up previous
Next: 1.2.9 Capitalization and Commenting Up: 1.2 Java Mechanics Previous: 1.2.7.2 Variations on the
Corky Cartwright
2000-01-07