| Author |
static initializers
|
jonas okwara
Ranch Hand
Joined: Jun 22, 2004
Posts: 58
|
|
Please could someone explain to me what static initializer is in this example: class Test { int a = 20; static { int b = 10; }
|
 |
Emilio Botella
Greenhorn
Joined: Sep 06, 2004
Posts: 6
|
|
|
In static block you've declarated a local variable, you may use it within a loop, for example to initiate others static variables.
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Static variables are initialized and static block is executed at class load time, which occurs either when the first object of that class is created or when a static member of the class is accessed (even if no object is created). If an object is being created, then instance variables are initialized and non-static initializer block is executed. After this, the body of the constructor executes. See thread: http://www.coderanch.com/t/246269/java-programmer-SCJP/certification/Initializers However, as Emilio pointed out, your int b is local to the block. If you want it accessible as a class variable, then you need to declare it as static outside of that block, even if you're going to initialize it using a static block. ( Barry change static b; to static int b; ) [ September 10, 2004: Message edited by: Barry Gaunt ] Thanks, Barry... [ September 10, 2004: Message edited by: marc weber ]
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
 |
|
|
subject: static initializers
|
|
|