5

For some reason when I create a new instance of an object from an existing instance and change values in the new instance, it also changes the values in the existing instance. I would prefer if it only changed the state of the values in the new instance though. I'm not sure why this is happening.

Foo existing = new Foo(1, "foo");

for (int i = 0; i < 10; i++) {
   Foo newFoo = existing;
   System.out.println(newFoo.getName()); //Prints "foo" as expected
   newFoo.setName("bar");
   System.out.println(existing.getName()); //This prints out "bar"?
}

Neither of the objects are static.

Temp
  • 53
  • 1
  • 1
  • 4
  • 2
    This -> `Foo newFoo = existing;` doesn't create a new instance of `Foo`. Just a new reference to the same instance. – Rohit Jain Mar 29 '15 at 19:49
  • If I was you I'd be looking at the clone() method, seen as you don't want to manipulate the first object, rather a clone of it.. – SpaceCowboy Mar 29 '15 at 19:49

7 Answers7

7

You can create a new instance at Runtime with:

Foo newFoo = existing.getClass().newInstance();

Note that the newly created instance will not be a copy of the existing one.

However, if you do need to a have a copy of the existing object, you can play a bit with the Clonable interface.

First, you have to make the Foo class implement the Cloneable interface:

public class Foo implements Cloneable { ... }

Then, you need to provide an implementation of the clone() method that will return a copy of you object:

public Foo clone() {
    return new Foo(this.id, this.name); //for example
}

And finally, you can invoke the newly introduced clone() method like this:

Foo newFoo = existing.clone();

This will give you a fresh Foo object, but with a copied properties from the existing one.

sciPher80s
  • 23
  • 4
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
1

Note that when you do

Foo newFoo = existing;

You are not creating a new instance. Instead, you are simply pointing the newFoo variable to the same object existing points to.

What you're doing is basically this:

Foo existing = new Foo(1, "foo")       <=> existing -> Foo(1, "foo")
Foo newFoo = existing                  <=> existing -> Foo(1, "foo") <- newFoo
newFoo.setName("bar")                  <=> existing -> Foo(1, "bar") <- newFoo
System.out.println(existing.getName()) <=> System.out.println(Foo(1, "bar").getName())

If you want to create a new instance you can do:

Foo newFoo = new Foo(existing.getId(), existing.getName());
Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
0

You are creating a new reference, not a new instance. Try something like this...

Foo newFoo = oldFoo.clone()

This preserves the original objects' values

Daniel K.
  • 1,326
  • 2
  • 12
  • 18
0

To create a copy of your Foo instance you could inherit from Cloneable and implement a clone() method as follows:

class Foo implements Cloneable {
  @Override
  public Foo clone() {
    try {
      return (Foo)super.clone();
    }
    catch(CloneNotSupportedException e) {
      throw new AssertionError(e);
    }
  }
}

(see http://docs.oracle.com/javase/8/docs/api/java/lang/Cloneable.html as well)

tomse
  • 501
  • 2
  • 7
0

Create a copy constructor:

public Foo (Foo another) {
    this.propertyA = another.propertyA;
    // etc.
}

Then, inside the for loop:

Foo existing = new Foo(1, "foo");

for (int i = 0; i < 10; i++) {
    Foo newFoo = new Foo(existing);
    // system out etc
}

This is the best way to copy instances of a class.

fps
  • 33,623
  • 8
  • 55
  • 110
0

You are not creating a new instance, you are just creating a new variable which points to the same instance.You either have to create a copy constructor or create a new instance with values of the existing instance as shown below :

Foo instance = new Foo(existing.getPropertyA(), existing.getPropertyB());
fastcodejava
  • 39,895
  • 28
  • 133
  • 186
-1

In the line

Foo newFoo = existing;

You are not creating a new instance of Foo; you are copying the reference of existing into the variable newFoo any actions taken on either existing or newFoo will affect the same underlying object

There is a very thorough discussion on how to copy an object in java here: How do I copy an object in Java?

Community
  • 1
  • 1
beresfordt
  • 5,088
  • 10
  • 35
  • 43