D.5. Notes on Declaring and Using Methods

There are three ways to call a method:

1. Using a method name by itself to call another method of the same class—such as maximum(number1, number2, number3) in line 21 of Fig. D.2.

2. Using a variable that contains a reference to an object, followed by a dot (.) and the method name to call a non-static method of the referenced object—such as the method call in line 13 of Fig. C.3, myGradeBook.displayMessage(), which calls a method of class GradeBook from the main method of GradeBookTest.

3. Using the class name and a dot (.) to call a static method of a class—such as Math.sqrt(900.0) in Section D.3.

A static method can call only other static methods of the same class directly (i.e., using the method name by itself) and can manipulate only static variables in the same class directly. To access the class’s non-static members, a static method must use a reference to an object of the class. 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 a non-static method directly. How would the method know which object’s instance variables to manipulate? What would happen if no objects of the class existed at the time the non-static method was invoked? Thus, Java does not allow a static method to access non-static members of the same class directly.

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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset