Copy of object by passing as method parameter

3k Views Asked by At

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?

4

There are 4 best solutions below

0
On BEST ANSWER

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.

1
On

First of all, new Object(o.getInnerObject()) won't compile, since Object doesn't have a matching constructor.

Assuming you replace it with new OuterObject (o.getInnerObject());, the new instance of OuterObject would contain the same instance of InnerObject that o contains, since the constructor of OuterObject doesn't create a copy of the InnerObject instance passed to it.

0
On

You get as much objects as you have created with the new keyword.

1
On

Your codes have compiling errors in this line: return new Object(o.getInnerObject()); o is an instance of Object.So, it cannot have a method like getInnerObject(); Also,Object does't have a constructor like Object(InnerObject). So,change

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

into

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

We can answer your question now. 'new' will always create an new object in heap memory,but the two outerObjects have the same innerObject reference.