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.
Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, choose Instances. Select the instance you want to use, and then choose Actions, Launch More Like This. The launch wizard opens on the Review Instance Launch page.
Step 1: Log in to your AWS management console. Step 2: Navigate to EC2 service and select your EC2 instance. Step 4: Provide name, description, reboot option, and tags for the image and click “Create Image”. Step 5: AMI image is created, now you can launch a new EC2 instance from this AMI.
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 Clonable
interface:
public class Foo implements Clonable { ... }
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 trigger 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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With