Java Reference
In-Depth Information
Static values are declared with the
static
keyword. For example, in this
class the variable
pi
is declared
static
:
public class
ConstHolder
{
public static double pi = 3.14;
}
When the JVM loads the byte code for the class description of
ConstHolder
,
it creates a single memory location for the
pi
variable and loads it with the
value 3.14. All instances of the
ConstHolder
class can access the exact same
value of
pi
. The
pi
data exists and we can access it even when no instance of
ConstHolder
is created. Since
pi
is a member variable of the class, though
a special one because it is static, it can be accessed just like any other member
variable. For example, if
g1
is an instance of
Test
, then we can access the
variable
pi
as follows:
ConstHolder c = new ConstHolder();
double twopi = 2.0 * c.pi;
If there is no instance of
ConstHolder
,wecan access the data directly using
the name of the class:
double twopi = 2.0 * ConstHolder.pi;
In practice, it is a good habit to always use the latter syntax, even when a class
instance exists, since it makes clear to the reader that the referenced variable is a
static member variable of the
Test
class.
In addition to static member variables, we can also define static methods,
producing methods that can be called without instantiating the class. For example,
public class
ConstHolder
{
public static double pi
=
3.14;
public static double getPI ()
{
return pi;
}
}
We could, in this case, use the
getPI()
method to obtain the value of
pi
:
double x
=
2.0 * ConstHolder.getPI ();
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. We've already
Search WWH ::
Custom Search