Search code examples
javaooppass-by-referencepass-by-valueobjectinstantiation

Copy of object by passing as method parameter


I am a bit confused about Java's pass by reference/values in method parameters.

I have a constructor in an OuterObject class:

private InnerObject io;
public OuterObject(InnerObject io){ 
    this.io = io;
}

public InnerObject getInnerObject(){
    return this.io;
}

If I pass an OuterObject into a copy method like this:

InnerObject io = new InnerObject();
OuterObject o = new OuterObject(io);    
anotherClass.getCopyOf(o);

and in another class:

public static OuterObject getCopyOf(InnerObject o){
    return new OuterObject(o.getInnerObject());
}

As you can see I create the OuterObject with the InnerObject as a parameter. Now I would like to know:

Do I get two new Objects from the return statement, or is it only a new OuterObject copy but same reference to the existing InnerObject?


Solution

  • If you store objects in variables or parameters you always store the reference. The object is never copied. Only primitive types, such as int or boolean are copied.

    If you want to create copies of objects you should look into object cloning using the java.lang.Cloneable interface and the Clone method or a copy constructor. What you choose is but a matter of preference. I usually perfer copy constructors as they show more clearly what is happening. At least for me.

    Also your line return new Object(o.getInnerObject()); will not compile. But I guess you wanted to write OuterObject instead of Object here.