Java Reference
In-Depth Information
3.6.4
instance members versus static members
Fields and methods declared with the keyword
static
are
static members
. If
they are declared without the keyword
static
, we will refer to them as
instance
members
. The next subsection explains the distinction between instance and
static members.
Instance members
are fields or meth-
ods declared with-
out the
static
modifier.
3.6.5
static fields and methods
A
static method
is a method that does not need a controlling object, and thus
is typically called by supplying a class name instead of the controlling object.
The most common static method is
main
. Other static methods are found in the
Integer
and
Math
classes. Examples are the methods
Integer.parseInt
,
Math.sin
, and
Math.max
. Access to a static method uses the same visibility
rules as do static fields. These methods mimic global functions found in
non-object-oriented languages.
A
static method
is a
method that does
not need a control-
ling object.
Static fields
are used when we have a variable that all the members of
some class need to share. Typically, this is a symbolic constant, but it need not
be. When a class variable is declared
static
, only one instance of the variable
is ever created. It is not part of any instance of the class. Instead, it behaves
like a single global variable but with the scope of the class. In other words, in
the declaration
Static fields
are
essentially global
variables with class
scope.
public class Sample
{
private int x;
private static int y;
}
each
Sample
object stores its own
x
, but there is only one shared
y
.
A common use of a static field is as a constant. For instance, the class
Integer
defines the field
MAX_VALUE
as
public static final int MAX_VALUE = 2147483647;
If this constant was not a static field, then each instance of an
Integer
would
have a data field named
MAX_VALUE
, thus wasting space and initialization
time. Instead, there is only a single variable named
MAX_VALUE
. It can be
accessed by any of the
Integer
methods by using the identifier
MAX_VALUE
. It
can also be accessed via an
Integer
object
obj
using
obj.MAX_VALUE
, as would
any field. Note that this is allowed only because
MAX_VALUE
is public. Finally,
MAX_VALUE
can be accessed by using the class name as
Integer.MAX_VALUE
(again allowable because it is public). This would not be allowed for a nonstatic
Search WWH ::
Custom Search