Java Reference
In-Depth Information
3.
Using the class name and a dot (
.
) to call a
static
method of a class—such as
Math.sqrt(900.0)
in Section 6.3.
A
static
method can call other
static
methods of the same class directly (i.e., using
the method name by itself) and can manipulate
static
variables in the same class directly.
To access the class's instance variables and instance methods, a
static
method must use
a reference to an object of the class. Instance methods can access all fields (
static
variables
and instance variables) and methods of the class.
Recall that
static
methods relate to a class as a whole, whereas instance methods are
associated with a specific instance (object) of the class and may manipulate the instance
variables of that object. Many objects of a class, each with its
own
copies of the instance
variables, may exist at the same time. Suppose a
static
method were to invoke an instance
method directly. How would the
static
method know which object's instance variables
to manipulate? What would happen if
no
objects of the class existed at the time the
instance method was invoked? Thus, Java does
not
allow a
static
method to directly
access instance variables and instance methods of the same class.
There are three ways to return control to the statement that calls a method. If the
method does not return a result, control returns when the program flow reaches the
method-ending right brace or when the statement
return
;
is executed. If the method returns a result, the statement
return
expression
;
evaluates the
expression
, then returns the result to the caller.
Common Programming Error 6.4
Declaring a method outside the body of a class declaration or inside the body of another
method is a syntax error.
Common Programming Error 6.5
Redeclaring a parameter as a local variable in the method's body is a compilation error.
Common Programming Error 6.6
Forgetting to return a value from a method that should return a value is a compilation
error. If a return type other than
void
is specified, the method
must
contain a
return
statement that returns a value consistent with the method's return type. Returning a value
from a method whose return type has been declared
void
is a compilation error.
To understand how Java performs method calls, we first need to consider a data structure
(i.e., collection of related data items) known as a
stack
. You can think of a stack as analo-
gous to a pile of dishes. When a dish is placed on the pile, it's normally placed at the top
(referred to as
pushing
the dish onto the stack). Similarly, when a dish is removed from
the pile, it's normally removed from the top (referred to as
popping
the dish off the stack).