Java Reference
In-Depth Information
Display 5.1
Static Methods (part 2 of 2)
Sample Dialogue
Enter radius:
2
A circle of radius 2.0 inches
has an area of 12.56636 square inches.
A sphere of radius 2.0 inches
has a volume of 33.51029333333333 cubic inches.
Within the definition of a static method, you cannot do anything that refers to a calling
object, such as accessing an instance variable. This makes perfectly good sense, because a
static method can be invoked without using any calling object and so can be invoked when
there are no instance variables. (Remember instance variables belong to the calling object.)
The best way to think about this restriction is in terms of the this parameter. In a static
method, you cannot use the this parameter, either explicitly or implicitly. For example,
the name of an instance variable by itself has an implicit this and a dot before it. So you
cannot use an instance variable in the definition of a static method.
Static Methods
A static method is one that can be used without a calling object. With a static method, you
normally use the class name in place of a calling object.
When you define a static method, you place the keyword static in the heading of
the definition.
Since it does not need a calling object, a static method cannot refer to an instance variable
of the class, nor can it invoke a nonstatic method of the class (unless it creates a new object
of the class and uses that object as the calling object). Another way to phrase it is that, in
the definition of a static method, you cannot use an instance variable or method that has an
implicit or explicit this for a calling object.
PITFALL: Invoking a Nonstatic Method Within a Static Method
If myMethod() is a nonstatic (that is, ordinary) method in a class, then within the
definition of any method of this class, an invocation of the form
myMethod();
means
this .myMethod();
(continued)
 
 
Search WWH ::




Custom Search