In the course of program development a need will often
arise for utility methods and constants of various sorts. Object
creation uses up memory resources so it is desirable to obtain access
to such resources without creating new objects.
We have seen, though, that Java does everything within classes.
There are no global variables, for example, as in C/C++ outside
of the class definitions.
To provide for such general resources, Java offers static
(also called class) data and methods that are contained
in a class definition but exist and can be accessed without creating
an instance of the class.
Note: We refer to non-static
data as instance data since the values belong to a unique
instance of the class.
For example, in this class the variable pi
is declared static.
public class
MyMathStuff
{
public static double
pi = 3.14;
}
|
When the JVM loads the byte code for the class description
of MyMathStuff,
it creates a single memory location for the pi
variable and loads it with the 3.14 value.
The pi
data exists and we can access it even when no instance of
MyMathStuff
is created.
We can access the data directly using the name of the class, as
in:
double
x = 2.0 * MyMathStuff.pi;
We could also define static methods that we can call without instantiating
the class. For example,
public class
MyMathStuff
{
public static double
pi = 3.14;
public static double
timesPI (double x)
{
return
x * pi;
}
}
|
We could, in this case, use the method to obtain
the product of pi
and a double value:
double
x = MyMathStuff.timesPI(2.3);
A static variable or method is also called a class
variable or method, since it belongs to the class
itself rather than to an instance of that class.
If a class property is also declared final
it is referred to as a constant since it cannot be altered:
class
MyMathStuff
{
public final static
double PI = 3.14;
}
|
This, in fact, is how the pi value Math.PI
is defined in the Math
class. By convention, the names of constants
are in uppercase.
The Math
class also contains static methods to carry out various mathematical
functions without creating a Math
object.
Note that class methods can only refer
to static data and to the data passed in the argument list. For
example, the following class contains a mix of static and non-static
data and methods. The static methods cannot refer to the non-static
data members of the class because values for those only exist for
instances of the class.
public
class
Test
{
public
final
static double PI = 3.14;
// static or "class" variable
double
b = 3; // non-static or "instance" variable
public
double func (double x)
{
return
(4.0 * Math.sin (x)**2);
}
public
static double
sfunc (double x)
{
return
(3.0 * x);
}
public
static double tfunc (double x)
{
return
(3.0 * x * PI);
}
public
static
double wfunc (double x)
{
return
(3.0 * x * b);// Error!
Cannot use nonstatic
variable b in a class
method.
}
}
|
Latest update: Oct. 17, 2004
|