Strange syntax for instantiating an inner class

前端 未结 6 1826
慢半拍i
慢半拍i 2020-12-05 09:12

I didn\'t imagine that I would encounter radically new syntax in Java anymore at this stage, but lo and behold, I just encountered something:

The exact context a

6条回答
  •  离开以前
    2020-12-05 10:16

    You actually can do that, but you have to declare ClickEvent as static inside Button, and then you shouldn't have any problem using you sintax:

    buttonClick(new Button.ClickEvent(button));
    

    Basically static makes the class ClickEvent belong directly to the class Button instead of a specific instance(i.e. new Button()) of Button.


    Following @Jon Skeet example:

    // Button.java
    class Button
    {
    
        public static class ClickEvent
        {
            public ClickEvent(Button b)
            {
                System.out.println("Instance: " + this.toString());
            }
        }
    }
    
    // Test.java
    public class Test
    {
        public static void main(String[] args)
        {
            Button button = new Button();
            buttonClick(new Button.ClickEvent(button));
        }
    
        public static void buttonClick (Button.ClickEvent ce) {
        }
    }
    

提交回复
热议问题