Invoking a method of an anonymous class

前端 未结 4 559
-上瘾入骨i
-上瘾入骨i 2020-12-09 07:27

I learned the other day that you can do this

new Object() {
    void hello() {
        System.out.println(\"Hello World!\");
    }
}.hello();
4条回答
  •  爱一瞬间的悲伤
    2020-12-09 08:07

    As posted, there isn't a way to get the anonymous methods from the Object instance. And, it makes Anonymous classes look pointless. But, you could (and I usually would) use it to implement an interface. Something like,

    static interface Hello {
        void hello();
    }
    public static void main(String[] args) {
        Hello o = new Hello() {
            public void hello() {
                System.out.println("Hello World!");
            }
        };
        o.hello();
    }
    

    Or, more commonly, for call-backs with JFC/Swing and ActionListener.

提交回复
热议问题