The Anonymous Class Conundrum

冷暖自知 提交于 2019-11-29 17:51:59
Petar Minchev

Anonymous classes can be recognized by the dollar sign and a number after it - Class$1.class. These classes are just for your own convenience. Imagine this:

class SaveButtonListener implements ActionListener {
  ...
}

class OpenButtonListener implements ActionListener {
  ...
}

This is very tedious. So you can create the implementation right away with an anonymous class. The compiler gives the name prepending the dollar sign and some identifier after it.

What happens behind the scenes is that Java creates a new inner class with an auto-generated name.

Feel free to ask questions if you find my explanation messy. I am tired now.

class A
{
    public A()
    {
        JButton btn = new JButton();
        btn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                // ...
            }
        });
    }
}

is more or less rewritten by the compiler as

class A
{
    private class SomeCuteName implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            // ...
        }
    }

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