If I have a class like the one below:
public class Foo()
{
private RandomObject randomObject = new RandomObject();
public RandomObject GetRandromObject()
{
return randomObject;
}
}
And in another class I do this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
RandomObject ro = fooObject.GetRandomObject();
ro.ChangeNumberVariable(23);
}
}
Will the fooObject have the randomObject NumberVariable changed to 23?
If not would I just have to have a method in Foo called SetRandomObject and just pass in ro? Would this be a good substitute for passing by reference in Java?
What if I just did this:
public class Goo()
{
private Foo fooObject = new Foo();
public Goo()
{
fooObject.GetRandomObject().ChangeNumberVarialbe(23);
}
}
Is it still not changing the NumberVariable?
In both cases fooObject.randomObject would have NumberVariable changed to 23. They are pretty much equivalent just the former uses an extra reference.
This does not make Java pass-by-reference. Java is pass by value. Any time you pass something to a method as a parameter it is copied, even if what you pass is a reference to an object.
Though you can use that copied reference to access and mutate the object on the end of it, as you are doing here, any re-assignment of that reference cannot escape the method.
In your first example doing:
would not change anything about fooObject.randomObject.