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

 
 
Content Index
Content Page # 18

Object variables ?references to objects in memory

Although an object can be created using a very simple new statement such as:

new String("stock items");
except in certain cases this is not very helpful, since we have no idea where in the computer this object has been created, and so it can never be referred to again by the computer system.
 
When a reference is not needed
Sometimes there are actions defined in the constructor method of a class, that mean an object once created and executing its constructor method can do whatever it is that we want ?without that object ever needing to be referred to again.


The new statement is actually an expression, which evaluates to a reference to the new object.

Therefore it is very easy to store the reference in a variable. We can declare a variable able to refer to an object of a certain class as follows:

<class> <variableIdentifier>;
For example:
String name1;
Ball ball1;
BankAccount customerAccount1;
At this point, these three variables do not refer to any objects (they have the value null).

It is now possible to assign to such a variable the reference to a newly created object:

name1 = new String("Julie Brown");
ball1 = new Ball();
customerAccount1 = new BankAccout("Fred", "Smith", 304.02, "deposit");
Like arrays and primitive types of variable, it is possible to combine the declaration of a variable, with the giving it an initial value. Thus:
String name1 = new String("Julie Brown");
Ball ball1 = new Ball();
both declare the variables name and ball1, and also make these variables refer to newly created objects of the String and Ball classes respectively.

Back to top

basicline.gif (169 bytes)

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