• 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

a question about scope and inner classes

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello I was using the santis self tester and was confused by the following problem:

// ...some code...

private void somethingLikeAMethod() {
double a =10;
String d="Weapon";
final String c = "Loaded";
final double b = 10;

class Class{
void method() {
System.out.println(Math.sin(a));
System.out.println(c+" "+d);
System.out.println(Math.rint(b));
}
}
}

// .. Some code...

The question is: Which variables can the inner class read (There are 2)?
I thought a and d, because they are final, but the answer is B,C and the reason given is: The scope of the variables a and d are to low. Can anyone provide a better explanation about why b and c are not in scope?

Thanks in advance.
 
Ranch Hand
Posts: 265
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Brent,

The example inner class you give can more specifically be called a local class.

A local class can only access the local variables of its defining scope if the variables are declared final.

The reason is, the compiler gives the local class access to the variables by automatically creating a private instance field to hold a copy of the variable, as well as creating hidden parameters in the constructor to automatically initialize those private instances.

This can only work if the variables to be copied are final, so that the local class can be guaranteed that its local values are the same as the instantiating scope.
 
Brent W Farrell
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Stevi your post cleared things up for me.
reply
    Bookmark Topic Watch Topic
  • New Topic