Sunday 15 May 2011

passing objects as parameters in java -



passing objects as parameters in java -

i'm trying create 2d game in java.

in process noticed many objects needed bounds (x1, x2, y1, y2) , consequence many methods had parameters (int x1, int x2, int y1, int y2).

so thought heck, why not create object intrectangle attributes x1, x2, y1, y2 (which set public performance boost), along few helpful methods getwidth(), getheight(), etc.

at point code much cleaner , haven't lost much performance since variables public.

i noticed, unlike passing primitive values method, values of passed object changed when changed them in method.

for instance, primitive value

`int x = 10;` subtract5(x); print(x); void subtract5(int i){ -= 5; }

this line of code print 10. object...

class xy{ public int x; public int y; } main { xy xy = new xy(); xy.x = 5; xy.y = 10; changex (xy); print xy.x } changex (xy xy2){ xy2.x = 7; }

it prints 7;

the theory i've developed int not pointer int, it's int stored in register. pushed when method called , popped when returned, unchanged. object reference object. object isn't pushed onto stack, pointer.

but i've tired strings (that know objects) , behave ints in matter, confuses me. perhaps create re-create out of somehow?

well, hope can shed lite on matter , tell me reasoning taking wrong turn , give me advice on how clean code, maintain performance, without making venerable.

a object in java block of memory in heap space. pass around references object/memory area. (the references passed value) if have object rectangle 4 ints methos alter memory of heap ara references passed object reference.

strings immutable - object cannot alter , every modifier method returns new instance.

see http://javadude.com/articles/passbyvalue.htm more information.

java object parameter-passing

No comments:

Post a Comment