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.x
to the return value of callingcompute
on the result ofgetX
which simply will returnb.x
, compute is defined for B asv -> v * 2
, which madex
equal to2
.
- The field was initialised at first with
-
Q2b: Answer -> 5
- The field started as
5
and callingb.work()
does not have any affect on c's instance fieldx
which leavesc.x
equal to 5.
- The field started as
-
Q2c: Answer -> 20
b.y
is actually referring to theA.y
static field, which started as10
but calling work doubled it's value to become20
.
-
Q2d: Answer -> 20
c.y
is actually referring to theB.y
field, (it will try to find ay
static field on the C class, and it will go up the inheritance tree to reference theB.y
static field), TheB.y
field 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.x
by 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 callingcompute
on the result ofgetX
getX
is defined on the A class level, and it will return the value2
since the value never changed for this instance since it has been initialised.- calling
compute
looks a little bit tricky, but thefinally
block 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
compute
instance 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 lastsetX
on the C instance was called with the value of 1, the new value ofc.y
(i.e B.y) is 1
- calling