Kevin Meredith
Kevin Meredith

Reputation: 41909

Java Reference to Objects

Let's say I have a Node class. It has a single field, Node parentNode. It's got setters and getters too.

I have 2 nodes: Node nodeA and Node nodeB.

Here's what I want to do: set nodeB's parent to nodeA's parent, and then set nodeA's parent to null.

  1. nodeB.setParent(nodeA.getParent());
  2. nodeA.setParent(null); // bad since nodeB.getParent() will = null

To achieve the above, must I clone nodeA, and then do nodeB.setParent(nodeAClone.getParent())?

Upvotes: 1

Views: 81

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213193

nodeA.setParent(null); // bad since nodeB.getParent() will = null

No, nodeB.parent will not be set to null. Java always uses Pass by Value and not pass by reference. Repeat it 10 times.

And in case you pass references, you pass them by value of references.


Let's understand in more detail.

When you do: -

nodeB.setParent(nodeA.getParent());

you simply create a copy of reference to nodeA parent, and store it in nodeB parent. So, you have now two references referring to nodeA parent object.Now, when you set nodeA parent to null, it is detached from that parent, but nodeB parent reference is still there.

Upvotes: 2

digitaljoel
digitaljoel

Reputation: 26574

Because nodeX.parent is a reference to an object:

  • When you call nodeB.setParent(nodeA.getParent()) you are saying to nodeB "here is the address of nodeA's parent."
  • When you then say nodeA.setParent(null); you are saying to nodeA "Forget where your parent lives. Your parent is now nothing."
  • You said nothing to nodeB in the second statement, which still has the address to what is now its parent.

Upvotes: 3

Related Questions