Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

reference

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?

like image 204
Matthew Piziak Avatar asked May 05 '10 19:05

Matthew Piziak


People also ask

How do you assign an object to an object in Java?

If we use the assignment operator to assign an object reference to another reference variable then it will point to the same address location of the old object and no new copy of the object will be created. Due to this any changes in the reference variable will be reflected in the original object.

How can we make a copy of a Java object?

The clone() method of the class java. lang. Object accepts an object as a parameter, creates and returns a copy of it.

Which method is used to create a copy from an existing object?

Utilize Object clone() method by calling super. clone() in overridden clone method, then make necessary changes for deep copying of mutable fields. If your class is serializable, you can use serialization for cloning.

How do you assign a reference to a new object in Java?

Assigning a reference type variable copies the reference out. println(joan); Person ball = joan; The statement Person ball = joan; creates a new Person variable ball , and copies the value of the variable joan as its value. As a result, ball refers to the same object as joan .


1 Answers

Java never copies objects. It's easiest to think of in terms of for each "new" you will have one object instance--never more.

People get REALLY CONFUSING when they discuss this in terms of pass by reference/pass by value, if you aren't amazingly familiar with what these terms mean, I suggest you ignore them and just remember that Java never copies objects.

So java works exactly the way you wanted your first example to work, and this is a core part of OO Design--the fact that once you've instantiated an object, it's the same object for everyone using it.

Dealing with primitives and references is a little different--since they aren't objects they are always copied--but the net effect is that java is just about always doing what you want it to do without extra syntax or confusing options.

like image 119
Bill K Avatar answered Oct 10 '22 03:10

Bill K