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

 
 
Content Index
Content Page # 12

Customer constructor example

The example below shows how to provide a class 'Customer' with a constructor.

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

  // Customer constructor
  Customer ()
  {
    // Statements to initialize the object go here
  }
 }

Note that the constructor in this case is defined as Customer(), so to create a new Customer object we would write:
new Customer();
Alternatively, let's suppose that when we create a new customer we will always specify the customer's name, address, account balance and credit limit. In this case we would define the constructor as follows:
// Customer constructor

Customer (String _name, String _address, 
                        int _accountBalance, 
                        int _creditLimit)
{
  // set the variavbles of the class from 
  // the constructor's parameters

name = _name;
address = _address;
accountBalance = _accountBalance;
creditLimit = _creditLimit;
 }
Then we might create a new Customer like this:
new Customer ("Fred Bloggs", "13 Acacia Avenue", 0, 2000);
Use of '_' prefix
Notice in the example above, rather than using a prefix like 'new' or 'item' for each argument, the prefix '_' was used. This is another convention widely used to distinguish between the names of arguments and the names of the variables they are setting. It is important, whichever convention you adopt for the identifiers of arguments, that you do not write methods that have either arguments or local variables that have the same identifiers as your object's variables.


Back to top

basicline.gif (169 bytes)

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