Java Reference
In-Depth Information
an array object. If two variables contain references to the same object, the state of the ob-
ject can be modified using one variable's reference to the object, and then the altered state
can be observed through the reference in the other variable.
Example 4.3.1-2. Primitive and Reference Identity
Click here to view code image
class Value { int val; }
class Test {
public static void main(String[] args) {
int i1 = 3;
int i2 = i1;
i2 = 4;
System.out.print("i1==" + i1);
System.out.println(" but i2==" + i2);
Value v1 = new Value();
v1.val = 5;
Value v2 = v1;
v2.val = 6;
System.out.print("v1.val==" + v1.val);
System.out.println(" and v2.val==" + v2.val);
}
}
This program produces the output:
i1==3 but i2==4
v1.val==6 and v2.val==6
because v1.val and v2.val reference the same instance variable (§ 4.12.3 ) in the one Value
object created by the only new expression, while i1 and i2 are different variables.
Each object is associated with a monitor (§ 17.1 ), which is used by synchronized methods
8.4.3 ) and the synchronized statement (§ 14.19 ) to provide control over concurrent access
to state by multiple threads (§17).
4.3.2. The Class Object
The class Object is a superclass (§ 8.1.4 ) of all other classes.
All class and array types inherit (§ 8.4.8 ) the methods of class Object , which are summarized
as follows:
• The method clone is used to make a duplicate of an object.
Search WWH ::




Custom Search