Sobes.tech
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.instanceNumber is 1, a.x is 1, and A.y (the static field) is 2.
  • The method doIt(z, a) is called with z=3 and a referencing the object with instanceNumber=1.
  • Inside doIt, i is a local copy of z (which is 3), so i = 11 does not affect z outside.
  • a.x = 12; sets the x of the object a points to, so a.x becomes 12.
  • a.y = 13; sets the static field y to 13.
  • a = new A(2); creates a new object with instanceNumber=2 and assigns it to local variable a. The original object remains unchanged.
  • a.x = 21; and a.y = 22; modify the new object.

After the method call:

  • The original object a still points to the first object with instanceNumber=1.
  • Its x is 12.
  • The static field y is 22.
  • The variable z remains 3.
  • The new object with instanceNumber=2 is not referenced after doIt.

Therefore:

  • a points to the original object with instanceNumber=1.
  • a.instanceNumber is 1.
  • a.x is 12.
  • a.y is 22.
  • z is 3.