The Anonymous Class Conundrum

后端 未结 2 1023
耶瑟儿~
耶瑟儿~ 2020-12-21 20:44

I think I understand the basics of Anonymous classes but I\'d like to clarify something. when I have a syntax such as this

class A
{
       class Anonymous         


        
相关标签:
2条回答
  • 2020-12-21 21:22

    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.

    0 讨论(0)
  • 2020-12-21 21:42
    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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题