Could two different objects contain equivalent data?
Yes. The objects would be constructed out of different bytes in memory, but would contain equivalent values.
Recall that objects have (1) identity, (2) state, and (3) behavior. "Identity" means that each object is a unique entity, no matter how similar it is to another. Here is a program that shows this situation:
class egString6
{
public static void main ( String[] args )
{
String strA; // reference to the first object
String strB; // reference to the second object
strA = new String( "The Gingham Dog" ); // create the first object.
// Save its reference
System.out.println( strA );
strB = new String( "The Gingham Dog" ); // create the second object.
// Save its reference
System.out.println( strB );
if ( strA == strB )
System.out.println( "This will not print.");
}
}
|
In this program, there are two objects, each a unique entity.
Each object happens to contain data equivalent to that in the other.
Each object consists of a section of main memory separate from the
memory that makes up the other object.
The variable strA
contains a reference to the first object,
and the variable strB
contains a reference to the second object.
Since the information in strA
is different from the information in strB
,
( strA == strB )
is false, (just as it was in a previous program with two objects.)
Since there are two objects,
made out of two separate sections of main memory,
the reference stored in strA
is different from the reference in strB
.
It doesn't matter that the data inside the objects looks the same.