Accessing an instance of a class from an anonymous class argument

I can not find the answer to this question through all the anonymous questions of the inner class on the site.

public void start()
{
    /* Ask the user to login */
    final LoginFrame login;
    login = new LoginFrame(new ActionListener()
    {
        @Override
        public void actionPerformed(final ActionEvent event)
        {
            switch (event.getActionCommand())
            {
                case "login":
                    /* @todo Login the user */
                    String username = login.getUsername();
                    String password = login.getPassword();
            }
        }
    });
    login.display();
}

In my registration frame is ActionListener. How to access loginfrom new ActionListener()?

Now I get the error message:

The login variable may not be initialized.

+4
source share
3 answers

AFAIK you cannot, because it ActionListenerwill be created first and at that time must have access to a final variable loginthat is not yet initialized.

The order of calls will be as follows:

  • create instance ActionListener
  • pass this instance to the constructor LoginFrame
  • login

, ActionListener login - .

, , ActionListener, i.e.

final LoginFrame login = new LoginFrame();
login.addActionListener( new ActionListener() { ... } );
+3

ActionListener LoginFrame.

login, , .

add, :

private final login = new LoginFrame();

login.addActionListener(
  new ActionListener()
  {
    @Override
    public void actionPerformed(final ActionEvent event)
    {
      switch (event.getActionCommand())
      {
        case "login":
          /* @todo Login the user */
          String username = login.getUsername();
          String password = login.getPassword();
      }        
    }      
  }
);    

login.display();
+1

login .

Through this, anonymous classyou initialize your variable so that it can be used after its initialization. And if you want to use this variable, you must initialize it (but never initialize your variable with a value null, because you use class methods LoginFrame, and it should throw NullPointerException).

0
source

Source: https://habr.com/ru/post/1533691/


All Articles