Why can an ActionListener access private class variables?

Hi, I am new to Java, and I have the following questions (I was already looking for a forum, but have not figured it out yet):

Why is it possible to access private class variables from actionlistener as follows:

public class Test{ private int x; Test(){ init(); } .... public void init(){ .... Button button_1 = new Button("buttonTest"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { x++; } }); } } 

And why can't I postpone the previous code (by creating the + actionlistener button) in the constuctor without errors ("x cannot be resolved")?

Hi

+4
source share
3 answers

Instead of writing x++; try using Test.this.x++;

The problem is that you are trying to access a data item from an anonymous inner class. If you write x++; , then it will be a reference to a local variable in the actionPerformed(ActionEvent arg0) method, which does not exist. Therefore, to refer to the class data member, you must use this , but since you are using an anonymous inner class, you must also specify the class name, so it becomes Test.this.x++; .

+2
source

This should solve this:

 public void actionPerformed(ActionEvent arg0) { Test.this.x++; } 
0
source

Why is it possible to access private class variables from actionlistener as follows:

Your actionListener class is inside your Test class. Therefore, the actionListener accesses the form of the private attribute inside the class, so privte is working fine. If you want to prevent the creation of a separate file for actionListener

0
source

All Articles