Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with instancevariable initialization

 
Ganesh Kumar
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test{
int x;
x=10;//Error on token ';' expected
}


Cant we initialize after declaring in the class.
What is the problem in the above program.Please clear me friends.
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that you cannot initialise variables inside the class body, unless it's done inside a static code block, the declaration of an anonymous class, or as part of a variable declaration.

The body of a class object is not 'executed' in the strict sense of the word when the object is created; What does happen is that all variables are initialised and assigned their specified (or default) values. A static block will be run the first time the class is loaded, from what I understand.

Jeremy
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But there is this kind of instance initialization block:

Frankly I don't know the proper name for it and I'd probably never use it because most human readers would throw a Huh? exception.

Note that it works just as well, and in a far more confusing way, anywhere in the file:
 
Ganesh Kumar
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks friends....
 
Michael Jennings
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

you must use an instance initialiser block to assign a value to the variable x, as


you cannot initialise an instance variable in a static initialiser block, because a static initialiser block, and "static-context" code, do not have access to instance members(variables and methods both).

1. a static initialiser block will be similar to above block, but will be qualified with keyword "static"
2. a static initialiser block is executed when the class is loaded. and, an instance initialiser block is executed when an instance of the class is created, i.e. when we do "new SomeClass()"
[ July 04, 2007: Message edited by: Michael Jennings ]
 
Jeremy Botha
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, if I ever saw code like the examples above in any system I was maintaining, I would track down the perpetrator and hit them with an axe. Hard. Using the sharp end

J
 
Ganesh Kumar
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Jenings
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic