文档介绍:专业译文
原文出处:
Passing & Returning Objects
By now you should be reasonably s h) {
("h inside f(): " + h);
}
public static void main(String[] args) {
PassReferences p = new PassReferences();
("p inside main(): " + p);
f(p);
(new String[] {
"%% p inside main\\(\\): PassReferences@[a-z0-9]+",
"%% h inside f\\(\\): PassReferences@[a-z0-9]+"
});
}
} ///:~
The method toString( ) is automatically invoked in the print statements, and PassReferences inherits directly from Object with no redefinition of toString( ). Thus, Object’s version of toString( ) is used, which prints out the class of the object followed by the address where that object is located (not the reference, but the actual object storage). The output looks like this:
p inside main(): ******@ad3ba4
h inside f(): ******@ad3ba4
You can see that both p and h refer to the same object. This is far more efficient than duplicating a new PassReferences object just so that you can send an argument to a method. But it brings up an important issue.
Aliasing
Aliasing means that more than one reference is tied to the same object, as in the preceding example. The problem with aliasing occurs when someone writes to that object. If the owners of the other references aren’t expecting that object to change, they’ll be surprised. This can be demonstrated with a simple example:
//: appendixa:
// Aliasing two references to one object.
import .*;
public class Alias1 {
private static Test monitor = new Test();
private int i;
public Alias1(int ii) { i = ii; }
public static void main(String[] args) {
Alias1 x = new Alias1(7);
Alias1 y = x; // Assign the reference
("x: " + );
("y: " + );
("Incrementing x");
++;
System.