This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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.
McFinnigan? Never heard of him. Nobody here but us chickens...<br /> <br />SCJP for Java 1.4<br />SCJD for Java 5.0
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 ]
Joined: Feb 16, 2005
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