aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubts regarding Method local inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubts regarding Method local inner class" Watch "Doubts regarding Method local inner class" New topic
Author

Doubts regarding Method local inner class

santu das
Greenhorn

Joined: Jan 02, 2009
Posts: 4
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

Joined: Aug 03, 2008
Posts: 9293
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
santu das
Greenhorn

Joined: Jan 02, 2009
Posts: 4
thanks a lot...it is somehow resolved my doubts..
Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 253

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.


Regards
Salil Verma
 
 
subject: Doubts regarding Method local inner class