File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

local classes..............

 
Rowan Chattaway
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class that resides within a method can only access final variables.....right?
The reason is, I'm looking at some code now that is implying that you can access final variables and instance variable of the outer class!?
Can an local class within a method of another class access that classes instance variables?
Rowan.
ps - the fear is upon me, exam on wednesday, and I did nothing on the weekend, due to hangover.......
 
amol re
Ranch Hand
Posts: 36
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. Yes. The local class does have access to the outer class variables.
2. If the local class is a non static class, it gets access to all the outer class variables.( static as well as non static ) But for this local class to be a non static class, the method encompassing it has to be a non static method so that outer context can be made available to the local class.
3. If the encompassing method is a static method, the local class *has* to be static. In that case, it can access only static variables of the outer class.
4. all this is in addition to the access it always gets to the final local variables declared in the encompassing method.
 
Rowan Chattaway
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so:
public class Outer
{
private int i = 9;
public Outer()
{};
public doSomething(final int f)
{
class Inner
{
System.out.println(f) //legal - final
System.out.println(i); //I was under the impression that this would be illegal, are you saying that a class defined in a method has access to the outer classes variable?
}

}
}
Rowan
 
Vanitha Sugumaran
Ranch Hand
Posts: 356
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rowan,
A local class defined in non-static method can access all members in of the outer class and local final variables.

A local class defined in a static method can access static members and local final variables.

Hope this helps,
Vanitha.
 
Rowan Chattaway
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's great! Cheers!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic