| Author |
MethodLocalClass Question
|
liqiang yang
Ranch Hand
Joined: Jan 20, 2008
Posts: 92
|
|
public class Test1 { public static void main(String[] args) { final int a=1; // Line 1 final int b; // Line 2 b=10; // Line 3 class MethodLocalClass { System.out.println(a); //Line 4 } } } Why it fails to compile on Line 4? Method Local Class can access its enclosing method's final var, right? Anybody can fix it? Thanks.
|
DY.
SCJP 5.0 (100%), SCWCD 5.0 (79%), SCBCD 5.0 (preparing...)
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by liqiang yang:
A nested class is just like any other class in that statements need to be inside methods.
|
"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
|
 |
Karl Prenton
Ranch Hand
Joined: Mar 10, 2008
Posts: 51
|
|
surround with braces i.e. an initialization block (non-static) : { System.out.println(a); //Line 4 }
|
 |
liqiang yang
Ranch Hand
Joined: Jan 20, 2008
Posts: 92
|
|
|
Thanks Frank, Can you explain a little bit, how it works?
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by liqiang yang: Thanks Frank, Can you explain a little bit, how it works?
If you place the statement inside braces within the class body, the block of code will execute when the class is initialized. This will allow your code to compile, but you won't see any output until an instance of the method local class is created. You could also place the statement inside a method, as I suggested above. [ March 18, 2008: Message edited by: marc weber ]
|
 |
 |
|
|
subject: MethodLocalClass Question
|
|
|