Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

chapter 3 self test question 5, K&B

 
Mauricio Archbold Babroza
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

why the answer is true true???
if the code the f1 and z does not have final the answer is the same???
 
Rajeev Rnair
Ranch Hand
Posts: 308
Java Linux Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mauricio Archbold Babroza wrote:
why the answer is true true???
if the code the f1 and z does not have final the answer is the same???


check carefully the FizzSwitch(Fizz x, Fizz y) method.


It assigns the first Fizz argument to a final Fizz z. Then you change the x variable, and return the same Fizz object, except that now Fizz.x = 6
Yes, you can change the object variables even if the object is declared final. Only thing you can't do with a final object is to re-assign it. For example, you cannot write


In effect you are passing f1 and f2 to fizzSwitch() method and getting back f1 (with f1.x = 6). The result is assigned to f3.
f1 and f3 will be the same because both f1 and f3 are references to the same object. Changes in either f1 or f3 will reflect each other because of this.


Eve if you take out 'final', result will be same. I think the final is added to create more confusion!

 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can change the state of a a final object but you cannot make the reference start referring to a new a object.

Best Regards,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic