Why we are making a variable as final in method inner class ?

Why we are making the variable as final (method inner class) while we are accessing the method variable in inner class ?
regards,
namanc

As far as I can tell, the only reason is to protect the programmer: when the inner class instance is constructed, it is given the then-current value of the variable. If the variable (or method parameter) later changes, the value held by the inner class would not. By making the variable final, the programmer doesn't have to worry about them staying in sync.
Here's some code to ponder:
public class InnerExample
    void printMe( final int x )
        Runnable runMe = new Runnable()
            public void run()
                System.out.println(x);
        (new Thread(runMe)).start();
}When compiled with the Sun JDK 1.4.2, you get this bytecode:
void printMe(int);
  Code:
   0:   new     #2; //class InnerExample$1
   3:   dup
   4:   aload_0
   5:   iload_1
   6:   invokespecial   #3; //Method InnerExample$1."<init>":(LInnerExample;I)V
   9:   astore_2
   10:  new     #4; //class Thread
   13:  dup
   14:  aload_2
   15:  invokespecial   #5; //Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
   18:  invokevirtual   #6; //Method java/lang/Thread.start:()V
   21:  returnAt line (byte) 5, it loads the passed value onto the stack; at line 6, it invokes the inner class constructor (which is created by the compiler). Nothing in this sequence of code would prevent use of a non-final variable.

Similar Messages

  • Inaccessible with local variable(non-final) via method local inner class

    Hi All,
    Usually local variables, including automatic final variable live on the stack and objects & instanace variables live on the heap.The contracts for using the method local inner class should allow merely method final variable, not non-final stack variable.
    Can anyone please clarify me ,behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?
    Is anything correlated with the stack and heap aspects?
    Thanks,
    Stalin.G

    [email protected] wrote:
    ...behind the scene what is actual fact why method inner class should not access the stack(method) variable and only allow final variable?...explained by dcminter and Jardium in [an older thread|http://forums.sun.com/thread.jspa?messageID=10694240#10694240|http://forums.sun.com/thread.jspa?messageID=10694240#10694240]:
    ...Final variables are copied into inner classes - that's why they have to be declared final; to avoid the developer making an incorrect assumption that the local variable can be modified and have the change reflected in the copy.
    When a local class uses a local variable, it doesn't actually use the variable. Instead, it takes a copy of the value which is contained in the variable at the moment the class is instantiated. It's like passing the variable to a constructor of the class, except that you do not actually declare any such constructor in your code.
    To avoid messy execution flows to be present in a Java method, the Java language authors thought it was better to allow a single value to be present in such a variable throughout all its life. Thus, the variable has to be declared final.
    ...HTH

  • Inner class inside a method - how does it access method's local variable?

    hello All:
    I've learnt that, an inner class, if defined inside a method, it can access the method's local variables, only when they are defined as "final".
    Anyone can help explain the rationale behind it?
    Thanks a lot!
    Sway

    fathomBoat wrote:
    In java, everything is about pass-by-reference.
    Wrong! Nothing in Java is ever pass-by-reference.
    Java uses pass-by-value everywhere.
    It makes sense to me if the reason of enforcing a variable to be "final" is to prevent it being messed up.No, the reason is that a copy is made and if the variable weren't final then it could change later on and the developer could be confused because his inner class didn't "see" that change.
    The variable being final prevents that scenario.
    However, if a copy of the variable is made inside the inner class, i dont see how possible it could affect variables outside of class?Such a copy is made, but the language designers wanted to hide that fact from the developer. By forcing all accessed variables to be declared final the developer has no way to realize that he's actually working on a copy.

  • Why go for a static inner class than a regular static class

    Hello,
    What are the reasons to go for a static inner class? What benefits are available with a static inner class when compared to a static class?

    When a class is an integral part of another class, it doesn't make sense to create a top level class for it.
    Also there is no "static class" only static inner class.

  • Why only final variables can be accessed in an inner class ?

    Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
    1. Why should i declare them as final ? What's the reason?
    2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.

    (Got an error posting this, so I hope we don't end up with two...)
    But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
    Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
    If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
    Or is there any alternate way?Any alternate way to do what?

  • What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?

    Hi All,
    I am new to TestStand. Still in the process of learning it.
    What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?
    Thanks in advance,
    LaVIEWan
    Solved!
    Go to Solution.

    Hi,
    Using the Parameters is the correct method to pass data into and out of a sub sequence. You assign your data to be passed into or out of a Sequence when you are in the Edit Sequence Call dialog and in the Sequence Parameter list.
    Regards
    Ray Farmer

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Why does the IPhone 4 get really hot, when you are making a phone call??

    I can't seem to find the answer to this riddle . why does the iPhone 4 get really hot when you are making phone calls or when using face Time ??

    It doesn't.
    There must be an issue with your iphone.
    Have you tried reset?  Restore?
    Have you made an appointment at the genius bar to have them look at it?

  • Why's a local instance is called final inside

    Hello everyone! I've a question. Suppose there is a code like below:
    public Component createComponents() {
    final JLabel label = new JLabel(labelPrefix + "0 ");//Why the instance label is called final?
    JButton button = new JButton("I'm a Swing button!");
    button.setMnemonic(KeyEvent.VK_I);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    numClicks++;
    label.setText(labelPrefix + numClicks);
    label.setLabelFor(button);
    JPanel pane = new JPanel();
    pane.setBorder(BorderFactory.createEmptyBorder(
    30, //top
    30, //left
    10, //bottom
    30) //right
    pane.setLayout(new GridLayout(0, 1));
    pane.add(button);
    pane.add(label);
    return pane;
    My question is why's the instance label is called final? I mean what's the explanation?
    Thankx.
    --DM

    But it is known that a local variable can be used
    anywhere inside a method public Component
    createComponents() {....}
    (according to the definition of local variable).Not sure what you're getting at here?? - in fact, I'm not even sure whether you're agreeing or disagreeing? The scope of a local variable is the inner-most block that it is declared in, which may or may not be an entire method.
    What should happen if another thread comes
    along and alters the value of the one in the nestedclass?
    Shouldn't the variable label be updated automatically
    as it's scope is inside the method
    createComponents()??But then local variables wouldn't be thread-safe (not in itself necessarily a reason not to do this, but it'd complicate things further and inner classes are only really syntactic sugar), and the existing access modifiers, security model and memory model wouldn't suffice for getting things working (which is IMHO a good enough reason).
    Think of this:
    public class MyClass {
        void myMethod() {
            final int myVar = 2;
            MyOtherClass obj = new MyOtherClass() {
                                    public void printVar() {
                                        System.out.println(myVar);
            //... do something with obj
    }as a shorthand for this:
    public class MyClass {
        void myMethod() {
            int myVar = 2;
            MyOtherClass obj = new MySubClass(myVar);
             //... do something with obj
        private class MySubClass extends MyOtherClass {
            private int myVar;
            MySubClass(int myVar) {
                this.myVar = myVar;
            public void printVar() {
                System.out.println(myVar);
    }In the second version you don't actually need to declare myVar final in the method (or in the class), because its been made explicit that the inner class has a copy of that variable (by passing it to the constructor), whereas in the first version its not so clear that that's what has gone on, but by making the variable final, you can think of it as there only being one copy of myVar (which still looks to be in scope). What you gain by using the first version is tighter scoping of the inner class (and shorter code).

  • HELP: Cannot refer to non-final variable inside inner class

    Below is a function that WAS working beautifully. I had to restructure many things in my code base to suit a major change and I have to make this function static. Since I made this function static, I get some errors which are displayed in comments next to the line of code.
    Can anyone offer any advice how to fix this?
    static private void patchSource( final Target target, final TargetResolver resolver, final TexSheetCommand args ) throws Exception
         boolean bDone = false;
         Element e;
         SAXReader sax          = new SAXReader();
         FileInputStream fis     = new FileInputStream( args.getInputFile() );
         Document document     = sax.read( fis );
         Element root = document.getRootElement();
         if( root.getName().equals( "Sheet" ) )
              XMLParser.iterateElements( root,     new XMLElementCallback()
                                                      public void onElement( Element element )
                                                           XMLParser.iterateAttributes( element,     new XMLAttributeCallback()
                                                                                                   public void onAttribute( Element element, Attribute attribute )
                                                                                                        if( attribute.getName().equals( "guid" ) )
                                                                                                             e = element; // PROBLEM: Cannot refer to a non-final variable e inside an inner class defined in a different method
                                                                                                             // WARNING: Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator<Attribute>
                                                                                                             for( Iterator<Attribute> it = element.attributeIterator(); it.hasNext(); )
                                                                                                                  Attribute a = (Attribute)it.next();
                                                                                                                  if( a.getName().equals( "randOffset" ) )
                                                                                                                       Integer i = new Integer( resolver.getTotalPermutations() );
                                                                                                                       a.setValue( i.toString() );
                                                                                                                       bDone = true; // PROBLEM: Cannot refer to a non-final variable bDone inside an inner class defined in a different method
              if( ( !bDone ) && ( e != null ) )
                   Integer i = new Integer( resolver.getTotalPermutations() );
                   e.addAttribute( "randOffset", i.toString() );                                                                                                                                            
         FileOutputStream fileOut     = new FileOutputStream( args.getInputFile() );          
         OutputFormat format               = OutputFormat.createPrettyPrint();          
            XMLWriter xmlWriter               = new XMLWriter( fileOut, format );
            xmlWriter.write( document );
            fileOut.close();
    }PS.) on a side note there is a warning on one of the lines too. Can anyone offer help on that one too?!
    Thanks in advance.

    It is already set to that - it does look correct in Eclipse, honest.
    It's just the block that's gone crazy with the formatting. I've spent around 10 minutes trying to tweak it just so it displays correctly but it wasn't making sense.
    I'd rather not turn this conversation into a judgement of my code-style - I already understand that it doesn't conform to the 'Java way' and I've had Java programmers bash me about it for a long time.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • Why would you declare a parameter as final ?

    "It is good practice to specify parameters that are class objects as final if you do not intend to alter them in a method."
    - Ivor Horton, Begining Java 2 .
    Why ?
    Declaring an object parameter as final or not still allows you to change the properties (instance variables) of the object. Rather, declaring the parameter as final only ensures that the reference to the object cannot be changed.
    Have i got this right ?
    Any help will be appreciated.
    Ezaz

    I often define my collections as final
    class Whatever {
      final ArrayList arList = new ArrayList();
    }Then you never have to test arList for null because any attempt to reset arList is flagged as a compiler error - e.g.
    arList = null;    // Compiler error
    arList = new ArrayList();    // Compiler errorThe compiler and/or JVM can also do any optimzations knowing this as well.

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • Local variable can't be accessed from inner class ???????? Why ??????

    Plesae help, help, help. I have no idea what to do with this bug.........
    <code>
    for ( int i = 0; i <= 2; i++ ) {
    for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    MyButton sub = grids[i][j];
    sub.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if ( sub.getState() == 0 ) {
         sub = new MyButton( (Icon) new ImageIcon(imageFile));
         if ( imageFile.equals("cross.jpg") ) {
              sub.changeState(1);
         else {
              sub.changeState(2);
    </code>
    The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

    OK, now I changed my code to this :
    for ( int i = 0; i <= 2; i++ ) {
      for ( int j = 0; j <= 2; j++ ) {
        grids[i][j] = new MyButton ();
        grids[i][j].setBorder(but);
        getContentPane().add(grids[i][j]);
        grids[i][j].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if ( grids[i][j].getState() == 0 ) {
               grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
              if ( imageFile.equals("cross.jpg") ) {
               grids[i][j].changeState(1);
              else {
              grids[i][j].changeState(2);
    [/cpde]
    Thanks for your advice !!!!!!
    Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

  • Why we are using cluster tables mainly HR

    can any plz tell me why we are using cluster tables mainly HR???

    Nice question -
    Am making my guess based on whatever little I know;
    PCLn are <i>file</i> systems and not a traditional (RDBMS) table system. Each File may contain one or more data clusters. SAP Defines data clusters thus -
    <i>A data cluster is a grouping of several data objects. Elementary fields, field strings and internal tables can be grouped in a data cluster</i>.
    <i>Example</i>:<i>Clusters B1 and B2 in files PCL1 and PCL2 are relevant to time evaluation, as is cluster PS, which stores the generated schema</i>.
    The reason why file system of data storage is used instead of DB Table system may be for the purpose of storing voluminous data (Payroll and time) and ease of retrieval during processing (RDBMS may hv tough time in this). Also probably because of SAP's origin from Mainframe.
    Why data clusters are used -? Probably data clusters are an offshoot (or part) of File system
    Pls feel free to contradict the above. Actually DB experts can throw more light on this..
    Regards
    Chandra

Maybe you are looking for

  • Account Posting

    Hi all Could you please tell me which Account and Transaction Key when posting: Example: Goods Receipt for Purchase Order Dr    Inventory Account                (BSX)     Cr    GR/IR clearing Account    (WRX) Could you please fill: Goods Issue for Se

  • IMessage on macbook pro won't sign in

    I just switched my phone company from Verizon Wireless to Vodaphone because i moved out of the US. Ever since I switched phone companies my imessage on my macbook pro will no longer connect. It still works fine on all of my other devices. I get an er

  • Ical bug on ipad application exits if I select 1 year ahead

    Anyone else get this. If I open the calender app on ipad 3 and select Mar 2013 the application just exits. - May be a bug with the same month one year ahead (Works ok if I select a different month) or just doesnt like Mar 2013

  • I can hear people but they can't hear me

    I can hear people but they can't hear me

  • Can't share screen using messages and ichat

    when i connect i can see my buddy and he can see me, but when i attempt to share his screen i get a white box across my screen and i can see his cursor moving but that is all i see. I had him ask to share my screen, which we did and he could see my s