File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

MethodLocalClass Question

 
liqiang yang
Ranch Hand
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by liqiang yang:

A nested class is just like any other class in that statements need to be inside methods.
 
Karl Prenton
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
surround with braces i.e. an initialization block (non-static) :

{
System.out.println(a); //Line 4
}
 
liqiang yang
Ranch Hand
Posts: 92
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Frank, Can you explain a little bit, how it works?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic