Reputation: 579
Consider the following:
public class Foo {
private String name;
public Foo(String name) {
this.name = name;
}
public String get() {
return name;
}
public void set(String name) {
this.name = name;
}
}
import java.util.ArrayList;
A container class:
public class FooContainer {
private ArrayList<Foo> foos;
public FooContainer(int nbrOfFoos) {
foos = new ArrayList<Foo>(nbrOfFoos);
}
public void add(Foo foo) {
foos.add(foo);
}
public void printFoos() {
for(Foo foo: foos) {
System.out.println(foo.get());
}
}
}
A simple test:
public class FooTest {
public static void main(String[] args) {
Foo foo = new Foo("Long");
FooContainer cont = new FooContainer(1);
cont.add(foo);
cont.printFoos();
foo.set("John");
cont.printFoos();
}
}
Of course, when executed, the test program prints "Long" and then "John".
Is it poor design to have a program where this is not desirable, i.e. where one would not like the name of the Foo to change?
Is the only workaround to copy/clone the object when passed to the add method?
Upvotes: 0
Views: 47
Reputation: 441
Just for clarification, Java always pass parameters as values. The misunderstanding comes as Java pass a copy of the reference thus it appears that an object is passed by reference.
Read this question to learn more: Is Java "pass-by-reference" or "pass-by-value"?
Upvotes: 0
Reputation: 8215
That's the way Java works: Objects are passed as reference and not as copies. In most cases, this seems to make sense. Copying an object can be expensive. If you want to put a copy into the container, you need to explicitly create a new object - I would not consider this a workaround.
If your point is mainly about preventing an existing object from being modified, you could make it immutable, i.e. make 'name' final and remove the 'set' method.
Upvotes: 3