• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

MethodLocalClass Question

 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Frank, Can you explain a little bit, how it works?
 
marc weber
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic