Page 254 - Introduction to Programming with Java: A Problem Solving Approach
P. 254

                220 Chapter 6 Object-Oriented Programming
Chapter 5 that many of the Java API methods return some kind of value, and in each case the type of value re-
turned is indicated by an appropriate return type in the method heading located at the left of the method name.
Returning a Value
If you look at the Mouse2 class in Figure 6.14, you’ll see that two of the methods have a return type that is different from void. Here is one of those methods:
   public int getAge()
{
return this.age;
} // end getAge
return type
return statement
   The return statement in this method allows you to pass a value from the method back to the place from which the method was called. In this case, the getAge method returns age to Mouse2Driver’s printf statement in Figure 6.13. Here is that statement again:
System.out.printf("Age = %d, weight = %.3f\n",
mickey.getAge(), mickey.getWeight());
method call
   In effect, the JVM “assigns” the return value (this.age) to the method call (mickey.getAge()). To per- form a mental trace, imagine that the method call is overlaid by the returned value. So if Mickey’s age is 2,
Apago PDF Enhancer
then 2 is returned, and you can replace the getAge method call by the value 2.
Whenever a method heading’s type is different from void, that method must return a value by means
of a return statement, and the type of that value must match the type specified in the method heading. For example, the getAge method heading specifies an int return type. The return statement within the getAge method returns this.age. In Figure 6.14, the age instance variable was declared to be an int, and that matches getAge’s int return type, so all is well. It’s OK to have an expression following the word return; you aren’t limited to just having a simple variable. But the expression must evaluate to the method’s return type. For example, would it be legal to use this?
return this.age + 1;
Yes,becausethis.age + 1evaluatestoaninttype,andthatmatchesgetAge’sreturntype.
When a method includes conditional branching (with an if statement or a switch statement), it’s possible to return from more than one place in the method. In such cases, all returns must match the type
specified in the method heading.
Empty return Statement
For methods with a void return type, it’s legal to have an empty return statement. The empty return
statement looks like this:
return;
The empty return statement does what you’d expect. It terminates the current method and causes control to be passed back to the calling module at the point that immediately follows the method call. Here’s a variation of our previous grow method that uses an empty return statement:
⎫⎪ ⎪ ⎬
⎪ ⎭




































































   252   253   254   255   256