Junior — Senior
Impact of methods on instance fields and static variables
livecode
Task condition
Here is the analysis of the code:
- After
A a = new A(1);,a.instanceNumberis 1,a.xis 1, andA.y(the static field) is 2. - The method
doIt(z, a)is called withz=3andareferencing the object withinstanceNumber=1. - Inside
doIt,iis a local copy ofz(which is 3), soi = 11does not affectzoutside. a.x = 12;sets thexof the objectapoints to, soa.xbecomes 12.a.y = 13;sets the static fieldyto 13.a = new A(2);creates a new object withinstanceNumber=2and assigns it to local variablea. The original object remains unchanged.a.x = 21;anda.y = 22;modify the new object.
After the method call:
- The original object
astill points to the first object withinstanceNumber=1. - Its
xis 12. - The static field
yis 22. - The variable
zremains 3. - The new object with
instanceNumber=2is not referenced afterdoIt.
Therefore:
apoints to the original object withinstanceNumber=1.a.instanceNumberis 1.a.xis 12.a.yis 22.zis 3.