wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Final class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about Final class" Watch "Question about Final class" New topic
Author

Question about Final class

Adrian Yan
Ranch Hand

Joined: Oct 02, 2000
Posts: 688
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

Joined: Jun 30, 2000
Posts: 1070
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

Joined: Nov 07, 2000
Posts: 26
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about Final class
 
Similar Threads
Variable hiding
Garbage Collection
A few questions!
Garbage collector!!!!!!!!!
Garbage collect from Sarga.com Exam