Hi
Background
I have a query based on Sierra & Bates
SCJP v6 Chapter 3 Question 5 and the effect of the final modifier. The essence of the query is the why the answer is correct. The notes to the question (pg 280) note that “The final modifier assures that a reference variable cannot be referred to a different object”.
I note that while f1 is not accessible from within the method FizzSwitch, the memory address of f1.x is. So when line 24 changes the initial x=5 to x=6 this is possible because fi, z and f3 refer to the same memory address. As shown in output “h)…”.
Query
I experimented with removal of the final for f1 and z and still get the same output (i.e. h) ….chapter03.Fizz@3e25a5). It appears that the reasoning that it is due to the final modifier does not hold. Without either and both the memory address is always the same. Hence f1.x is changed regardless of the 'final' modifier or just ‘default’.
Code enclosed code for ease of reference
Note there are extra System.out.println() to show details during execution.
Which gives the output
a) f1.x= 5
b) f2.x= 5
e) paramater x= 5
e) paramater y= 5
h) z= chapter03.Fizz@3e25a5
f) z.x= 5
g) z.x= 6
c) f1.x= 6
c) f3.x= 6
c) f2.x= 5
true true
h) f1= chapter03.Fizz@3e25a5
h) f3= chapter03.Fizz@3e25a5
Regards
Scott