Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

reference - How can Java assignment be made to point to an object instead of making a copy?

In a class, I have:

private Foo bar;
public Constructor(Foo bar)
{
    this.bar = bar;
}

Instead of creating a copy of bar from the object provided in the parameter, is it possible to include a pointer to bar in the constructor such that changing the original bar changes the field in this object?

Another way of putting it:

int x = 7;
int y = x;
x = 9;
System.out.print(y); //Prints 7.

It is possible to set it up so that printing y prints 9 instead of 7?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When a variable is used as argument to a method, it's content is always copied. (Java has only call-by-value.) What's important to understand here, is that you can only refer to objects through references. So what actually happens when you pass a variable referring to an object, is that you pass the reference to the object (by value!).

Someone may tell you "primitives are passed by value" and "non primitives are passed by reference", but that is merely because a variable can never contain an object to begin with, only a reference to an object. When this someone understands this, he will agree that even variables referring to objects are passed by value.

From Is Java "pass-by-reference" or "pass-by-value"?

Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.

From http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

In Java, there is no counter part to the C++ "reference type" for primitives.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...