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

 
 
Content Index
Content Page # 16

Methods ?customer example

Continuing with the Customer example: suppose we need the program to be able to print each customer's account balance on the screen (perhaps using System.out.println() or Graphics.drawString() ). A sensible place to put the instructions for this is in a method called `printBalance' (for example). We might define this method like this:

class Customer
{
  String name;
  String address;
  int accountBalance;
  int creditLimit;

  // printBalance method
  // prints the customer's balance

   public void printBalance ()
   {
      System.out.println 
              ("Current balance for " 
               + name 
               + " is " 
               + accountBalance
               + " pounds");
   }
}

In a specific object of this class, assume the customer's name is Fred Bloggs and the account balance is 2,000 pounds, then executing this method would print:
Current balance for Fred Bloggs is 2000 pounds
Look carefully at the start of the definition of printBalance:
public void printBalance ()
The keyword `public' loosely means `can be called by methods outside this class'. This concept is discussed in more later this unit.

The keyword `void' means that this method has no return value ('output'). The empty parentheses (brackets) mean that the method has no arguments ('inputs'). 

It is often pointed the printBalance does have a form of output: it produces an output on the screen. This confusion is the reason why we tend to use the term 'return value' here rather that 'output'. When it is said that printBalance has no return value, what is meant is that it would be meaningless to write a line like:

x = printBalance();
because nothing useful would be put into the variable x in this case. In other words, there is no output in the form of a reply returned to the message statement that invoked the method.

Back to top

basicline.gif (169 bytes)

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