Non-final variable inside an inner class - my nemisis

I have an issue with accessing variables from an inner method. This structure seems to allow access to the text objects but not to the button object. This comes from a bit of example code that just illustrates a simple form window with text fields and buttons that read them.
At the start of the class I have text objects defined like this:
public class SimpleGUI extends Composite {
Text nameField;
Text junkField;
// Constructors come next, etc...
Later within this class there is a method to create some GUI stuff, and then to create a button and when pressed access and print the text to the console
protected void createGui(){
junkField = new Text(entryGroup,SWT.SINGLE); //Ross
junkField.setText("Howdy");
Button OKbutton = new Button(buttons,SWT.NONE);
OKbutton.setText("Ok");
OKbutton.addSelectionListener(
new MySelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
System.out.println("Name: " + nameField.getText());
System.out.println("Junk: " + junkField.getText());
And that all works fine. So within the inner class, the object junkField can be accessed nicely.
However if I try to do the same with the button (I want to change the label on the button after it's pressed) I get errors for trying to access a non-final object in an inner class.
I tried to handle the button similar to the text, adding this after the text defs:
     Button myButton;
and under the println's in the inner class I wanted:
if OKbutton.getText.equals("OK") {  OKbutton.setText("NotOK")}
That's when I get an issue with "cannot refer to a non-final variable inside an inside class defined in a different method"
Now, if I move the button declaration into the createGui method, and declare it with "final Button myButton" it works.
Why does the button need different treatment than the text?
Is this a suitable method to make my button change it's label when pressed, or is this sloppy?

Button is a local variable. The anonymous inner class object you create can continue to exist after the method ends, but the local variables will not. Therefore, as the error message says, you must make that local button variable final if you want to refer to it inside the anon inner class. If it's final, a copy of its value can be given to the inner class--there's no need to treat it as "variable."

Similar Messages

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

  • 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

  • Local variable accessed within inner class

    Hey everybody,
    My program keeps telling me that it wont work because one of my methods is calling a local variable inside an inner class. Does anyone know what this means and how to fix it?
    Heres the code:
    public class SliderExample extends JPanel{
    int value=0;
    public SliderExample(int imw, int imh, Image img, BufferedImage buf, Graphics2D biCon){
    super(true);
    this.setLayout(new BorderLayout());
    JSlider slider= new JSlider(JSlider.HORIZONTAL,0,imw,25);
    slider.setMinorTickSpacing(10);
    slider.setMajorTickSpacing(100);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    JButton redraw= new JButton("Scroll");
    redraw.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ev){
    reDraw(slider,img,buf,biCon,imw,imh);
    add(slider,BorderLayout.CENTER);
    add(redraw,BorderLayout.AFTER_LINE_ENDS);
    public void reDraw(JSlider slid, Image im, BufferedImage bf, Graphics2D biC, int iw, int ih){
    value=slid.getValue();
    Graphics g= getGraphics();
    g.drawImage(im,value,0,iw,ih,this);
    g.drawImage(bf,value,0,iw,ih,this);
    biC.drawImage(bf,value,0,iw,ih,this);
    Any ideas???
    THanks,
    Rick

    Its getting them from another class thats calling the mothod to construct the slider bar with dedraw button. Thats a pretty big class but I will post the code where I called the method:
    public class Process extends JFrame implements MouseListener, MouseMotionListener{
    private int [][] points;
    private int [] lengths={0};
    private int [] bin;
    private String imstr;
    private String imsav;
    private int imgw=658;
    private int imgh=512;
    private int xArrayPos=0;
    private int yArrayPos=0;
    private int xpos=0;
    private int ypos=0;
    private int xprev;
    private int yprev;
    private int xadd;
    private int yadd;
    private String filstr;
    Image image;
    SimpleGUI gui;
    BufferedImage buffer;
    Graphics2D biContext;
    Graphics2D g2;
    BufferedImage last;
    Graphics2D lastContext;
    public Process(){
    JFrame slideFrame = new JFrame("Please slide to scroll image");
    slideFrame.setContentPane(new SliderExample(imgw, imgh,image,buffer,biContext));
    slideFrame.pack();
    slideFrame.setVisible(true);
    Thats what anything having to do with that function in the other class that calls the Slider Class.
    Do you know how I can fix this??
    Thanks,
    Rick

  • Reason for not allowing static declarations inside an inner class

    Is the reason for not allowing static declarations inside an inner class is due to the fact that it can never be accessed at a class level as the outer class has to create an instance of the inner class and any attributes/methods of the inner class has to be accessed through that.
    Typically, an instance (non-static) variable can never be accessed in a statement or expression inside a static context but the class variable can be accessed inside a non-static context. Given this, shouldnt the static declarations be allowed inside an inner class?
    Correct me if my understanding is wrong.
    Thanks

    I still couldnt get it clearly. Why i cant i have a static value ( variable ) for all the instances of the inner class irrespective of its enclosing instances of it ( i.e outer class instances). Say in this example below,
    class Outer
    static int i = 0;
    public Inner inner = new Inner();
    class Inner // inner class ( non-static nested class )
    int j = 0;
    static final int k = 2; // compile time constants are allowed
    // ininner class
    public void m1()
    j++;
    System.out.println("j is " + j);
    i++
    System.out.println("i is " + i);
    public static void main(String[] arg)
    Outer outer1 = new Outer();
    outer1.inner.m1(); // j will be 1 & i will be 1
    Outer outer2 = new Outer();
    outer2.inner.m1() // j will be 1 again & i will be 2. But I would
    // want j to be 2. Why is this not allowed?
    Looks like something missing..

  • Error message: "Attempt to use a non-final variable..."

    I get the following error message
    "....java:771: Attempt to use a non-final variable rightColumn from a different method. From enclosing blocks, only final local variables are available.
              switchToOrderform4( backArrow_J, fwdArrow_J, rightColumn, c, jobticketEnclosure ); // ------- the problem line"
              ^
    The variable is "rightColumn."
    I instantiate it in one class, "Class1."
    Pass it as a parameter to second class, "Class2."
    Pass it as a parameter to a third class, "Class3."
    Pass it as a parameter to a method, "method1( ... )."
    -- Declared & instantiated here, passed as a parameter to
    class Class1 extends JPanel {
         private JLabel rightColumn;
    class Class2 extends MouseAdapter {
    JLabel rightColumn,
    --Passed as a method paramter, causing the compiler error (line 771):
    class Class3 extends JPanel {
    Line 75:      JLabel rightColumn;
    Line 165:                          JLabel rightColumn,
    Line 255:      this.rightColumn = rightColumn;
    Line 771:           method1( backArrow_J, fwdArrow_J, rightColumn, c, jobticketEnclosure ); // ------- the problem line
    Declaring the variables final does not help. How do I fix this?
    Many thanks in advance.

    Hmm that's a puzzler. I would love to see a complete (but minimal) example of this.
    You might get more insight by using a different compiler, since you'd get a different version of the error message. Some compilers are more lucid than others.

  • How to access the int variable in the inner class

    hi all,
    i can't access the int variable in the inner class. can any one help me
    int count = 0;
    MouseMoveListener mouseMove = new MouseMoveListener() {
         public void mouseMove(MouseEvent e) {
              count1++;
              System.out.println(count);
    };how to access count variable
    thanks

    for this how can i access the countIf the count variable is a local variable you can't access it from within the
    inner class. Make it a member variable of the outer class instead:public class Outer {
       private int count;
       MouseMoveListener mouseMove= new MouseMoveListener() {
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }Alternatively, if you don't need that count variable anywhere else, you
    could simply make it a member variable of the inner class itself:public class Outer {
       MouseMoveListener mouseMove= new MouseMoveListener() {
          private int count;
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }kind regards,
    Jos

  • Synchronize on objects held in non-final variables?

    [This thread|http://forums.sun.com/thread.jspa?messageID=10775877#10775877] and post got me thinking:
    linuxisbest.eric wrote:
    I have noticed in my textbook that it creates a String in two ways:
    String a = new String("Hello");and
    String a = "Hello";Which one should I use? Is there any practical difference?
    YoungWinston wrote:Pick door number two linux ... unless you plan on synchronizing on it, that is.
    WinstonIs it best practice to only synchronize on objects held in final variables?
    Edited by: Encephalopathic on Jul 26, 2009 5:46 AM

    gnat wrote:
    Is it best practice to only synchronize on objects held in final variables?
    Above [best practices|http://en.wikipedia.org/wiki/Best_practices] apply to cases when lock is not intended to change.
    I think that there could be cases when lock is actually intended to change and therefore shouldn't be final. Here's an example of caching code I've seen recently:
    private final ConcurrentMap<Integer, Object> pendings
    = new ConcurrentHashMap<Integer, Object>();
    public Object loadEntity(int entityId) {
    Object lock = new Object(); // shouldn't be final, see below
    Object prev = pendings.putIfAbsent(entityId, lock);
    if(prev != null) {
    // without using prev lock, there would be a chance
    //  for concurrent threads to perform redundant invocation
    //  of retrieveEntityFromSomewhereSlowly for same entityId
    lock = prev;
    Object res;
    synchronized (lock) {
    res = getEntityFromCacheQuickly(entityId);
    if (res == null) {
    // cache miss - retrieve entity slowly:
    res = retrieveEntityFromSomewhereSlowly(entityId);
    pendings.remove(entityId);
    gnat,
    Huh? Please could you try to talk me through that code... At first glance, I don't follow it... I think it's still got "unprotected race conditions", but after reading it through several times (in the course of trying to frame a post saying basically "I don't think that will work, and here's why" I now think I understand how it does work (almost all the time), but I'd just really really like some validation of my mis/understanding.
    So... Here's how I think that works... please could you verify or repudiate my understanding.
    package forums;
    import java.util.Random;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.ConcurrentHashMap;
    class GnatsThreadsafeCache
      private static final Random random = new Random();
      // pending locks := entityId --> lock
      private final ConcurrentMap<Integer, Object> pendingLocks = new ConcurrentHashMap<Integer, Object>();
      // cache := entityId --> entity
      //          1        --> "1"
      private final Map<Integer, Object> cache = new HashMap<Integer, Object>();
      public Object loadEntity(int entityId) {
        Object lock = new Object(); // shouldn't be final, see below
        // putIfAbsent: If the specified key is not already associated with a value,
        //  associate it with the given value. Returns the previous value associated
        //  with the specified key, or null if there was no mapping for the key.
        Object previousLock = pendingLocks.putIfAbsent(entityId, lock);
        if(previousLock != null) {
          // without using previousLock lock, there would be a chance
          //  for concurrent threads to perform redundant invocation
          //  of retrieveEntityFromSomewhereSlowly for same entityId
          lock = previousLock;
        Object entity;
        synchronized (lock) {
          entity = getEntityFromCacheQuickly(entityId);
          if (entity == null) {
            // cache miss - retrieve entity slowly:
            entity = retrieveEntityFromSomewhereSlowly(entityId);
            addEntityToCache(entityId, entity);
        pendingLocks.remove(entityId);
        return entity;
      private Object getEntityFromCacheQuickly(int entityId) {
        DEBUG("> getEntityFromCacheQuickly("+entityId+")");
        Object entity = cache.get(entityId);
        DEBUG("< getEntityFromCacheQuickly returns "+entity);
        return entity;
      private Object retrieveEntityFromSomewhereSlowly(int entityId) {
        DEBUG("> retrieveEntityFromSomewhereSlowly("+entityId+")");
        try{Thread.sleep(random.nextInt(1000));}catch(InterruptedException e){System.err.println(e);}
        Object entity = Integer.toString(entityId);
        DEBUG("< retrieveEntityFromSomewhereSlowly returns "+entity);
        return entity;
      private void addEntityToCache(int entityId, Object entity) {
        DEBUG("| addEntityToCache("+entityId+", "+entity+")");
        cache.put(entityId, entity);
      public static void main(String[] args)
        final GnatsThreadsafeCache cache = new GnatsThreadsafeCache();
        for (int i=0; i<10; i++) {
          new Thread(
            new Runnable() {
              @Override
              public void run() {
                int i = random.nextInt(4);
                Object entity = cache.loadEntity(i);
                DEBUG("~ "+i+"-->"+entity);
          , "Thread"+i).start();
      private static void DEBUG(String message) {
        System.err.println(Thread.currentThread().getName()+": "+message);
    }How it works:
    1. create a new lock object.
    2. check if entityId exists in the previousLock list... that's a ConcurrentMap so the putIfAbsent operation is atomic (i.e. syncronised on the previousLock object).
        ~  This operation is "garanteed fast"; ergo it involves no heavy "business object" creation/retrieval.
    3. Now, if the entityId already exists in the previousLock list we syncronize on it, allowing one-thread-at-a-time to traverse "the crytical block" where we check if the-entity associated with the-given-entityId is allready cached, and retrieve it, otherwise create a new one (which will take an arbitrary "long time").
    So what? Well I think it means that we've reduced contention to the individual entity level, as apposed to the "collection level"; as you would get if you just used a "standard" ConcurrentMap as the cache... which means that we've (probably) increased the throughput because each thread is blocked only upon those other threads which definately would stuff-them-up (waiting for the heavy "business object" creation routine to complete); as apposed to those that just might stuff them up (but won't because they're actually retrieving different entities).
    In short: It's a way of blocking on distinct keys?
    Is that correct?
    Thanx in advance for your thoughts.
    Cheers. Keith.
    Edited by: corlettk on 1/08/2009 11:05 ~~ Removed extranious cache.get from retrieveEntityFromSomewhereSlowly.

  • Error with inner Classes

    I've a Swing app in wich I've the following code :
    final ComboBoxEditor editor = comboBox.getEditor();
    editor.getEditorComponent().addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyReleased(KeyEvent e) {
    combo_keyReleased(e,editor);
    Runned in a normal way it works, runned via Webstart 1.4.2 it gives me :
    java.lang.ClassFormatError: it/axioma/basic/application/templates/ClWidgetCombo$2 (Illegal Variable name " val$editor")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(Unknown Source)
         at java.security.SecureClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$100(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
    etc...
    Could someone explain me why ?
    Is there any workaround ?
    TIA
    Tullio

    There seems to be a problem using final variables with anonymous inner classes under a different classloader, see http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

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

  • Problem with final variables and inner classes

    variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
    Is there any solution to this?
    Exception is:
    java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
         at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
         at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
         at java.awt.Component.processMouseEvent(Component.java:5131)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

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

  • Final in inner class

    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?
    Thanks!
    int SIZE = 1; //somewhere else
            for( int size = 0 ; size < 5 ; size++){
                  Circle circle = new Circle(D/Padding);
                  circle.setOnMousePressed(new EventHandler<MouseEvent>(){
                      public void handle(MouseEvent me){
                          SIZE = size;
             );edit:
    I am well aware this isnt neccesarily a javafx specific thing, but more of a general java poor programming knowledge.
    I also know that the mouseadapter is an anonymous class and can only access final.
    I am just looking for any suggestions on how to best handle this.
    Edited by: namrog on Jul 5, 2011 10:51 AM
    Edited by: namrog on Jul 5, 2011 10:59 AM

    namrog wrote:
    I am trying to manually make a drawing program similar to this one
    http://javafx.com/samples/Draw/
    However I am running into issues involving inner classes and finals.
    "local variable size is accessed from within inner class; needs to be declared final"
    It wants me to make either SIZE or size a final. However once final, I can't change the variable.Yes, that's the point. If a local variable is to be used by an instance of a nested class, that nested instance can live on long after the local variable goes out of scope. So it needs its own, separate copy of the variable. However, since, as far as we are concerned, there is only one variable, that variable needs to be final, so that there will not be issues with keeping the two copies' values coherent.
    I have often used the variable in a for loop to assign a value(though maybe it was a bad practice?) however I am not sure the best way to handle this.
    Any suggestions?Create a final variable and copy the value of your non-final variable to it.
    int nonFinal =...;
    final int theFinalCopy = nonFinal;
    new Whatever() {
        void doStuff() {
          doSomething(theFinalCopy);
    }

  • 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 ???

Maybe you are looking for

  • How to monthly wise  report in XL -Reporter

    Hi, How to define monthly  wise report & How to use date function in XL-Reporter. thanks. Ruheena Tasneem

  • How to represent # in hyperlink URLs

    I have a series of URLs that I want to use in hyperlinks, that all have a hash character in them. The hash character is necessary to load the page properly. However, when I enter the URL "as is", the hash becomes %23 in the address bar, and the page

  • MACBOOK PRO RETINA (10.8.3) SLOW SHUT DOWN

    Hi, I just upgrade my OS X 10.8.3 2.3ghz intel core i7, and now the time to shut down increase dramatically, also i instal Traktor Pro 2. What should i do? Regards, Daniel

  • 11.5.10 ROI를 통해 SERIAL AND LOT CONTROLLED ITEMS을 처리하는 방법

    제품: Applications 작성날짜 : 2006-05-30 11.5.10 ROI를 통해 SERIAL AND LOT CONTROLLED ITEMS을 처리하는 방법 ======================================================== PURPOSE 11.5.10 Receiving Open Interface(ROI)를 통해 Serial and Lot Controlled Items을 처리하기 위해 어떤 interfa

  • Flash install problems - what else...

    Hi, I also have big troubles with that new Flash Version. I tried to install it several times, it also seems to work - the "test" page tells me that i have the latest version - and yet i cant open some Pages in the web browser. they tell me that i ha