您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)

 
 
Content Index
Content Page # 14

Return value

The return value is the 'output' of a method in the same way that the arguments are the 'input'.

The return value is the result that a method sends back as a reply (to the message that caused the method to be performed on an object). This is particularly important when the purpose of the method is to allow other objects to find out something about this object (i.e. get methods). The 憇omething?becomes the return value. 

The return value of a method is the reply returned to the message statement that invoked the method.. Writing data to the screen, to a window or to a file is not a return value. The return value has a type, like a variable.

Continuing with the customer example again: suppose we need to calculate the interest on a customer's account balance. Suppose further that we don't want to print this interest, but use it in a later calculation. What we need here is a method that returns the interest on the account. Then we can write something like:

double interest = calculateInterest();
// ... use the variable `interest' in another calculation
We might define the method calculateInterest()like this (note that for brevity I had omitted the rest of the class definition; don't forget that this method is really inside the class Customer. 
public double calculateInterest ()
{
  double newInterest = <interest_calculation>;
  return newInterest;
}
Note that this method's definition starts public double, and not public void. It returns a double value to the rest of the program. The actual value that is returned is indicated by the statement
return newInterest;
Note that name of the variable newInterest inside the method calculateInterest()only has a meaning inside that method. We could just as well have written:
public double calculateInterest ()
{
  double stupidName = <interest_calculation>;
  return stupidName;
}
and this would not affect any other part of the program.

Novice programmers often become confused about the difference between `output' as a return value, and `output' to, for example, the screen. For example, the operation `println' is defined as having no return value (technically called a void return). But it does produce an `output' to the display. Remember that a return value is an `output' only to another part of the program, not to some other part of the computer.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg