Static Methods

Often it is useful to have methods perform some function that does not depend on the contents of any object. Such a method can be defined as a static method. The following project file contains the programs described below.

For example, the Math class provides static methods for performing common mathematical calculations, as demonstrated by MathDemo.java. Another example is the Character class, which provides static methods for testing and operating on characters and is demonstrated by StaticCharMethods.java. Note that the pattern for calling a static method is:

class.method(parameters)

Defining Static Methods

MyMath.java demonstrates how to define static methods; MyMathTest.java contains a main method that tests them.

The MyMath class defines a class constant and three static methods that are intended to behave like their Math class counterparts. Note how the static keyword is used.