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

 
 
Content Index
Content Page # 20

Object individuality

Each object has individuality. So when a new object is created, it takes up its own part of the computer's memory. The individuality of an object is not related to the values of its variables (i.e. its state).

Consider the following statements:

LibrayItem book1;
LibrayItem book2;

book1 = new LibraryItem("Programming in Java", "J. Smith");
book2 = new LibraryItem("Java programming", "M. J. Jones" );

Two new objects have been created, which are instances of the class LibraryItem. The first new object was created, and the variable book1 assigned the reference to its location. The second new object was created in a different place in the computer's memory, and the variable book2 assigned the reference to that object.

Now consider the following:

LibrayItem book3;
LibrayItem book4;

book3 = new LibraryItem("Program in C", "J. Smith");
book4 = new LibraryItem("Program in C", "J. Smith");

Just the same thing has happened as before ?two different objects have been created, and each one is stored in a different location in the computers memory. Variable book3 refers to the first of these 2 new objects, and book4 refers to the second of these new objects. Although both these objects have been created with the same arguments (and so most likely have the same state) they are not the same object. It is perfectly reasonable to consider that there might be two copies of the same book in a library, but they are not the same objects.

Therefore, book3 does not have the same value (i.e. reference) as book4. Were we to use the boolean test for equality:

(book 3 == book4)
this would result in an evaluation to false.

Back to top

basicline.gif (169 bytes)

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