• Post Reply Bookmark Topic Watch Topic
  • New Topic

Working of final keyword  RSS feed

 
Khuzema Dharwala
Ranch Hand
Posts: 61
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

I have written the following program just to understand the working of "final" non access modifier.




When I compile this program it gives me

>javac TestOne.java
TestOne.java:4: cannot assign a value to final variable id
public void updateId(int newId) { id = newId; }
^
1 error


The error is self explanatory that you can't change the contains of variable marked final, the only doubt I have is why the same error not thrown inside constructor's code ?

Thanks...
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Khuzema Dharwala wrote:The error is self explanatory that you can't change the contains of variable marked final, the only doubt I have is why the same error not thrown inside constructor's code ?

You are allowed to initialise a final variable (there wouldn't be much point to them otherwise). This initialisation can either be done when you declare the variable (line 2 in your code) or in the constructor.
 
Khuzema Dharwala
Ranch Hand
Posts: 61
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stuart...much appreciated
 
Ishan Pandya
Ranch Hand
Posts: 228
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That same applies to method/stack variables also. Offcourse they cant be initialized through constructor.
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stuart A. Burkett wrote:This initialisation can either be done when you declare the variable (line 2 in your code) or in the constructor.

Or... In an initialization block.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!