Java Reference
In-Depth Information
Class Methods
As with class fields,
class methods
are declared with the
static
modifier:
public
static
double
radiansToDegrees
(
double
rads
)
{
return
rads
*
180
/
PI
;
}
This line declares a class method named
radiansToDegrees()
. It has a single
parameter of type
double
and returns a
double
value.
Like class fields, class methods are associated with a class, rather than with an
object. When invoking a class method from code that exists outside the class, you
must specify both the name of the class and the method. For example:
m
g
O
// How many degrees is 2.0 radians?
double
d
=
Circle
.
radiansToDegrees
(
2.0
);
If you want to invoke a class method from inside the class in which it is defined, you
don't have to specify the class name. You can also shorten the amount of typing
required via the use of a static import (as discussed in
Chapter 2
).
Note that the body of our
Circle.radiansToDegrees( )
method uses the class field
PI
. A class method can use any class fields and class methods of its own class (or of
any other class).
A class method cannot use any instance fields or instance methods because class
methods are not associated with an instance of the class. In other words, although
the
radiansToDegrees()
method is defined in the
Circle
class, it cannot use the
instance part of any
Circle
objects.
One way to think about this is that in any instance, we always
have a
this
reference to the current object. But class methods
are not associated with a specific instance, so have no
this
reference, and no access to instance fields.
As we discussed earlier, a class field is essentially a global variable. In a similar way, a
class method is a global method, or global function. Although
radiansToDegrees()
does not operate on
Circle
objects, it is defined within the
Circle
class because it is
a utility method that is sometimes useful when working with circles, and so it makes
sense to package it along with the other functionality of the
Circle
class.
Instance Fields
Any field declared without the
static
modifier is an
instance ield
:
public
double
r
;
// The radius of the circle
Instance fields are associated with instances of the class, so every
Circle
object we
create has its own copy of the
double
field
r
. In our example,
r
represents the radius