• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about Final class

 
Adrian Yan
Ranch Hand
Posts: 688
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
01: public class Final
02:{
03:private int val = 0;
04:
05:void set (int i) { val = i; }
06:
07:static public void main(String a[])
08:{
09:final Final anObj = new Final();
10:anObj.set(10);
11:anObj.val = 10;
12:
13:Final bObj = new Final();
14:anObj = bObj;
15:}
16:}
----------------------------------------------------------------
The answer is:
Compilation error at line 14. Cannot assign or change a final variable
can someone please explain?
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In line 9, you defined anObj as being final, that means you can't make it reference something else later on because it is final. So in line 14, when you try to say anObj = bObj, compiler says, "nope can't do that, you told me anObj can't be changed and now you are changing it". Of course the compiler abbreviates that to "Cannot assign or change a final variable"
Bill
 
ashwini srinivasan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Adrian Yan:
01: public class Final
02:{
03:private int val = 0;
04:
05:void set (int i) { val = i; }
06:
07:static public void main(String a[])
08:{
09:final Final anObj = new Final();
10:anObj.set(10);
11:anObj.val = 10;
12:
13:Final bObj = new Final();
14:anObj = bObj;
15:}
16:}

Hi adrian,
You cannot change a final object reference variable.
Here, anobj may not receive a new value.
But you can change data owned by an object that is referred to by a final object reference variable. So line 14 is illegal.
Read robert, heller book. It has been given clearly in chapter modifiers (other modifiers section).
regards,
ashwini.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic