Reputation: 1984
I'm currently working with code that has multiple instances of a particular class. Each instance runs through certain tasks, and collects data that is sent to a display layer for display. The problem that is occurring is that when a new instance of the class is created, it resets all other instances of that class that currently exist. Here's an example that will hopefully illustrate my point
Foo instanceFooOne = fooService.performActions(data);
Foo instanceFooTwo = fooService.performActions(data);
class FooService {
public void performActions(Object data) {
Foo foo = new Foo();
return foo;
}
}
To me, this should have two separate instances of the Foo object, but instead has only the latest version of Foo for all instance of the Foo object created. Is there any way to not have this happen?
Upvotes: 1
Views: 90
Reputation: 3652
You need to save the reference of data. Your currently only referencing memory for "data" so all other instances will change.
Foo instanceFooOne = fooService.performActions(data);
Foo instanceFooTwo = fooService.performActions(data);
class Foo{
private Object data;
public Foo(Object data) {
this.data = data;
}
public Object getData(){
return data;
}
}
Then use:
instanceFooOne.getData();
To quote Gevorg:
Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing the same Object no matter what!
Upvotes: 1