harry wrote:
I have an object that's passed in to a function as a parameter i.e public
boolean getProjectTitle(ProjectHeader_DTO obj) {...}
If I then call a method on this object inside the function i.e
obj.setTitle("test") then using obj.getTitle() from outside the function it
displays the property set correctly!
But doing something like this inside the function doesn't -
ProjectHeader_DTO x = new ProjectHeader_DTO();
x.setProjectTitle("test");
obj=x;
As long as I explictly set the properties it works but why not when
assigning another object?
When you call a function, the parameters are copied and only a copy of
the varible is used inside the function ( this is why passing int x does
not change x outside the function )
When you pass an object, not the object itself is passed but a pointer
to the memory of the object, the pointer is copied, but still shows to
the same memory. So obj.setTitle("test") inside the function changes the
title from the object obj points to ( and this is the same mermory, obj
outside the function points to ). When you create a new object x, x
points to some other memory. The statement obj=x says: make obj point to
where x points to ( to the newly allocated memory ). Assuming x was
created inside the function, x gets destroyed, as soon as you leave the
function. After the function, obj still points to the old obj-memory,
because the obj you assigned to x is only a copy of obj
think of it as houses and addresses: You have a green house ( you need
memory (space) for your house ) and you have a piece of paper with its
address: 5th avenue. If you copy or change the address on the paper, you
don't change anything about your house.
consider following pseudo-code:
void clean_house ( House green ) // passing copy of your paper with address
{
green.make_house_nice_and_clean(); // address points to the green house
}
-> green house is clean now!
void clean_house ( House green)
{
House red = new House; // building a new house somewhere else
green = red; // Address now indicates the red house
green.make_house_nice_and_clean(); // cleaning the red house!!!!
}
-> green house is still dirty
If you tell somebody to clean your house, it is impossible, to "give"
him the house, you rather leave the address - same with java: coping and
moving around all the mermory for the house is much less efficent than
passing the address to this mermory.
Hope this was helpful for you, if not, read your java Textbook again ;)