How can I access enclosing class instance variables from inside the anonymous class?

ⅰ亾dé卋堺 提交于 2019-12-02 01:38:12

How do I access instance variables from inside the anonymous class's method ?

You simply access them if need be:

class Tester extends JFrame {

   private JButton button;
   private JLabel label;
   //..some more

   public Tester() {
        function(); // CALL FUNCTION
   }

   public void function() {
      Runnable r = new Runnable() {
         @Override
         public void run() {
            System.out.println("Button's text is: " + button.getText());
         }
      };
      new Thread(r).start();
   }
}

More important: Why isn't this working for you?

What you are looking for is a fully qualified address since they are not marked final

final Runnable r = new Runnable() {
public void run() {
    Tester.this.button // access what you need
    Tester.this.label  // access what you need
}};

You use the same access pattern for Anonymous Inner Classes when building ActionListeners and other things as well.

This is explained in the specifications as 15.8.4 Qualified this, something the down voter apparently hasn't read. And didn't read the code for comprehension either.

the following code may explain you the format is IncloseingClassName.this.VariableName;

class Tester extends JFrame {
int abc=44;//class variable with collision in name
int xyz=4 ;//class variable without collision in name
public Tester() {
function(); // CALL FUNCTION  
}
public void function() {
Runnable r = new Runnable() {
int abc=55;//anonymous class variable
     @Override
     public void run() {
      System.out.println(this.abc);  //output is 55        
      System.out.println(abc);//output is 55 
      System.out.println(Tester.this.abc);//output is 44 
      //System.out.println(this.xyz);//this will give error
      System.out.println(Tester.this.xyz);//output is 4 
      System.out.println(xyz);//output is 4 
            //output is 4 if variable is declared in only enclosing method 
            //then there is no need of Tester.this.abcd ie you can directly 
            //use the variable name if there is no duplication 
            //ie two variables with same name hope you understood :)

     }
  };
  new Thread(r).start();
   }  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!