Skip to content

Instantly share code, notes, and snippets.

@chermehdi
Created June 20, 2020 23:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chermehdi/02a26bf22605261bf916a6d3734f5890 to your computer and use it in GitHub Desktop.
Save chermehdi/02a26bf22605261bf916a6d3734f5890 to your computer and use it in GitHub Desktop.
Explanation of the behaviour of a java exercice.

Answers with a bit of explanation

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 that a.work() was called which changed the current value of a.x to the return value of calling compute on the result of getX which simply will return b.x, compute is defined for B as v -> v * 2, which made x equal to 2.
  • Q2b: Answer -> 5

    • The field started as 5 and calling b.work() does not have any affect on c's instance field x which leaves c.x equal to 5.
  • Q2c: Answer -> 20

    • b.y is actually referring to the A.y static field, which started as 10 but calling work doubled it's value to become 20.
  • Q2d: Answer -> 20

    • c.y is actually referring to the B.y field, (it will try to find a y static field on the C class, and it will go up the inheritance tree to reference the B.y static field), The B.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 calling c.work() so the value is still 4.
  • Q2f: Answer -> 1

    • calling c.work() will set x to the value gotten by calling compute on the result of getX
    • getX is defined on the A class level, and it will return the value 2 since the value never changed for this instance since it has been initialised.
    • calling compute looks a little bit tricky, but the finally block is the last thing that is going to get executed so this will return 2 / 2 = 1, so the value of x has been set to 1.
  • 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.
  • Q2j: Answer -> 1

    • calling c.work() didn't only set the value of x but it also did set the value of B.y, and since the last setX on the C instance was called with the value of 1, the new value of c.y (i.e B.y) is 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment