I am confused about how Java deals with aggregation within objects, and in particular referencing of objects. It seems like objects will keep a reference to an aggregated object when it is passed as a parameter, rather than copying it like I've been lead to believe.
Say I have a basic class called Foo which contains a string attribute, print function, and setter for the text attribute.
public class Foo {
private String text;
public Foo(String text) {
this.text = text;
}
public void print() {
System.out.println(text);
}
public void setText(String text) {
this.text = text;
}
}
And a class called Bar which contains an attribute of type Foo, and a method called print which calls foos print method.
public class Bar {
private Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
public void print() {
this.foo.print();
}
}
If I define an instance of Foo, pass it into a new instance of Bar, and then call bars print method it will print "hello" as I expected. However if I then set the text of the original instance of foo to "Edited" using its setter method, bars print method will also print "Edited".
public static void main(String[] args){
Foo foo = new Foo("Hello");
Bar bar = new Bar(foo);
bar.print();
foo.setText("Edited");
bar.print();
}
The Bar object appears to be keeping a reference to the Foo object even though I passed it as a parameter. I'm sure I am missing something trivial here, and I just wanted someone to explain this clearly.