Setzer22
Setzer22

Reputation: 1689

Working with references and new

What's the expected behaviour of executing this line of code?:

Foo f = someOtherObject.getFoo(); //We get a reference of a Foo object from another class
f = new Foo();

Would someOtherObject.getFoo() return the new object, or the old one?, and what if we change the second line of code with:

f = null;

Would someOtherObjct.getFoo() return null, or the old object?

Upvotes: 2

Views: 96

Answers (6)

Mingyu
Mingyu

Reputation: 33379

When you assign different values/objects to f, you simply let f point to different memory locations, the memory that f points to does not get changed.

Foo f = someOtherObject.getFoo();

f points to object returned by someOtherObject.getFoo() (some memory location on the heap)

f = new Foo();

f points to a new object (another memory location on the heap)

Would someOtherObject.getFoo() return the new object?

Nope... because we did not change someOtherObject

f = null;

Would someOtherObject.getFoo() return the null?

Nope... because we did not change someOtherObject

Upvotes: 2

assylias
assylias

Reputation: 328785

You can think of f as containing a value that points to some object in memory. When you reassign f with f = something, it just changes the location in memory to which f is pointing.

But that does not affect the object f was pointing to originally.

So in both cases, getFoo() will return the old object even if your reassign f (assuming your getFoo method does not change anything and is a simple getter of course).

Upvotes: 5

AzureFrost
AzureFrost

Reputation: 67

f is just a pointer to an object, so changing where it points to (f = something else) does not change the object it was previously pointing to.

Example: (f being the kind of pointer you have)

f = existingobject;
f = otherobject;

All this means is that f first points to existingobject. When the next line is executed, f no longer points to existingobject but now points to otherobject. existingobject is entirely unaffected.

Upvotes: 0

SamYonnou
SamYonnou

Reputation: 2068

In both cases the value that someOtherObject.getFoo() returns is not affected. By reassigning f you reassign f itself, not the reference that f previously held.

Upvotes: 0

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

Foo f = someOtherObject.getFoo(); //Assign f to value returned by getFoo()
f = new Foo();                    //Reassign f to newly constructed Foo object
f = null;                         //Reassign f to null

In either case the getFoo() method doesn't care what you assigned to f.

Upvotes: 1

rocketboy
rocketboy

Reputation: 9741

f = null does not affect the object returned by getFoo() in anyway. or f = new foo() for that matter.

In both the cases, We are just changing the reference which f is holding.

Upvotes: 0

Related Questions