Note: If some answer does not make sense, or it's not well explained I apologise, please leave a question in the gist.
-
Q2a: Answer -> 4
- The field was initialised at first with
2, after thata.work()was called which changed the current value ofa.xto the return value of callingcomputeon the result ofgetXwhich simply will returnb.x, compute is defined for B asv -> v * 2, which madexequal to2.
- The field was initialised at first with
-
Q2b: Answer -> 5
- The field started as
5and callingb.work()does not have any affect on c's instance fieldxwhich leavesc.xequal to 5.
- The field started as
-
Q2c: Answer -> 20
b.yis actually referring to theA.ystatic field, which started as10but calling work doubled it's value to become20.
-
Q2d: Answer -> 20
c.yis actually referring to theB.yfield, (it will try to find aystatic field on the C class, and it will go up the inheritance tree to reference theB.ystatic field), TheB.yfield was created with a value 20 and hasn't modified since, so the answer is 20.
-
Q2e: Answer -> 4
- Nothing changed regarding this instance field
b.xby callingc.work()so the value is still 4.
- Nothing changed regarding this instance field
-
Q2f: Answer -> 1
- calling
c.work()will set x to the value gotten by callingcomputeon the result ofgetX getXis defined on the A class level, and it will return the value2since the value never changed for this instance since it has been initialised.- calling
computelooks a little bit tricky, but thefinallyblock is the last thing that is going to get executed so this will return2 / 2 = 1, so the value of x has been set to1.
- calling
-
Q2i: Answer -> 10
- the value of b.y was 20 as seen in Q2c, but calling work will change the
value of the static member to the result of calling
computeinstance method of C which will result in halving the old value of y and make it to 10.
- the value of b.y was 20 as seen in Q2c, but calling work will change the
value of the static member to the result of calling
-
Q2j: Answer -> 1
- calling
c.work()didn't only set the value of x but it also did set the value ofB.y, and since the lastsetXon the C instance was called with the value of 1, the new value ofc.y(i.e B.y) is 1
- calling