0

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?

Nate-Wilkins
  • 5,364
  • 4
  • 46
  • 61

1 Answers1

2

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:

ro = new RandomObject();

would not change anything about fooObject.randomObject.

Brian Smith
  • 3,383
  • 30
  • 41
  • So as long as I don't reassign the object I get out of GetRandomObject it will change the fooObject.randomObject? – Nate-Wilkins Aug 10 '12 at 21:48
  • I hate to say it, but Java has some C pointer semantics. C is always pass by value, and pointers too, get sent by value. – jn1kk Aug 10 '12 at 21:49
  • 2
    Using the call-by-value/call-by-reference distinction does very little but to confuse anyone talking about java. http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing – Falmarri Aug 10 '12 at 22:04
  • I don't think introducing another term helps any. IMO the distinction is useful if you ever have to maintain code that uses pass-by-reference in a language that supports it. It's potentially a blind spot for programmers who've only worked with Java or languages with similar semantics, the implications of reference changes escaping local scope are not obvious and often very confusing so it's worth understanding. – Brian Smith Aug 10 '12 at 22:39