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

Doubts regarding Method local inner class

 
santu das
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Regarding method local inner class:

In the below code i cannot access "z" from the inner class- it gives a compilation error, due to scope problem...
as "z" is local variable(blows away once the method gets completed) and for the inner class object that will be even the method gets completed(it will resding in the heap.)



class MyOuter2 {
private String x = "Outer2";
void doStuff() {
String z = "local variable";
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Local variable z is " + z); //Won't Compile!
} // close inner class method
} // close inner class definition
} // close outer class method doStuff()
} // close outer class


My question is marking the local variable as final resolves the issue?Please anybody exlpain once what happens when a variable is marked as final... will it be going to reside on heap...!!!
 
Ankit Garg
Sheriff
Posts: 9497
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santu please Use Code Tags when you post a source code. You can edit your message using button and then add code tags to it.

When you make a variable final, then the compiler knows that the value of that variable will not change once it is assigned. So the compiler gives the method local inner class a local copy of the variable when you instantiate the method local inner class. Read this discussion if it helps...
 
santu das
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot...it is somehow resolved my doubts..
 
Salil Vverma
Ranch Hand
Posts: 255
Hibernate Oracle Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Ankit /santu ,

the compiler knows that the value of that variable will not change once it is assigned. So the compiler gives the method local inner class a local copy of the variable when you instantiate the method local inner class.


I think,there is a slight correct here that it does not give the local copy of variable but compiling (creating the byte code), the compiler replaces all the existances of final variable with corresponding value. As in the below example -



The code after compilation in byte code would become as mentioned below -



In the inner class the variable would not be available but its value would be replaced at the compile time. I hope this would clear all of your doubts.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic