• Post Reply Bookmark Topic Watch Topic
  • New Topic

Changing a field's value outside of method?  RSS feed

 
Rob Akerfeldt
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, from my observations, it seems that after initialization, you can only change a field's value inside of a method body. Changing it outside of any method body causes an error. Example:



This code won't successfully compile for me. However, if I put the value reassignment of nacho to 5 inside of a method body, everything's just fine:




This code works just fine. This behavior appears to be the same for both static and instance fields. Can someone please explain why this is? Why can't I change the field's value outside of a method? Why is it ok to change its value inside of a method body? I've googled this quite a bit but can't seem to find an answer. Much appreciated.
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is correct, once a Class Variable or Instance Variable declared and optionally initialized to a value, then they can only be changed in a valid code segment that has visibility to that variable.
 
Rob Akerfeldt
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. And by "valid code segment", do you mean a method body/constructor body/block?
 
Les Morgan
Rancher
Posts: 779
19
C++ Java MySQL Database Netbeans IDE Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have to have a valid code scope, that, at this time, can be interpreted to mean method body.
 
Campbell Ritchie
Marshal
Posts: 56587
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Les Morgan wrote:. . . can only be changed in a valid code segment that has visibility to that variable.
Remembering that all fields are visible everywhere inside their own class . . .

If you write i = 5; that is a statement, and statements are not allowed to float loose in the class outside methods (etc). Should you add a type, that becomes a declaration and ceases to be a statement: int i = 5;
Field declarations are allowed to be loose inside the class and outside methods; where else could they be? Of course you can't declare the same variable twice in the same scope.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!