Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

final - access modifier

 
Mayur Ramgir
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found following statement in SCJP 5.0 Study guide;

"A reference variable marked final can never be changed, but the object it refers to can be modified."

Can anybody explain in detail?

Thanks in advance..
 
Vassili Vladimir
Ranch Hand
Posts: 1585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Let's suppose that you have the following:



This means when you say:



You will get a compilation error, which means that reference itself is final not the state of the object.

And let's suppose that SomeClass has a property named x, this means that you can do the following:



Without any problems.

Again, a final reference means that you can not refer to another object in the heap, but, you can change the state of the object that this final reference is refering to!

Best of luck ...
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
well,i am not sure but still try
to explain the above
with a small example as below
consider for example there are two classes
class A and class B





i hope it helps you to some extent!!!
[ September 26, 2007: Message edited by: dhwani mathur ]
 
sarada chellu
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the below Example hepls you better

class Test1
{
int i=10;
public static void main(String args[])
{
final Test1 obj1=new Test1();
obj1.i=20; //works fine! since you are changing the value of i but not obj1 memory
System.out.println(obj1.i);
Test1 obj2=new Test1();
obj1=obj2 // complilation error obj1 is final and trying to change obj1 memory.
}
}
 
Mayur Ramgir
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much guys!!! Much appreciated.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic