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
Joined: Feb 16, 2005
Posts: 125
posted
0
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
McFinnigan? Never heard of him. Nobody here but us chickens...<br /> <br />SCJP for Java 1.4<br />SCJD for Java 5.0
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
0
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:
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Ganesh Kumar
Ranch Hand
Joined: Jul 02, 2007
Posts: 113
posted
0
Thanks friends....
Michael Jennings
Greenhorn
Joined: Jul 04, 2007
Posts: 20
posted
0
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
Joined: Feb 16, 2005
Posts: 125
posted
0
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