Class definition inside method argument in Java?

前端 未结 4 1343
你的背包
你的背包 2020-12-16 01:39

I have come across Java code in this form for the first time:

object.methodA(new ISomeName() {
public void someMethod() {
//some code
}
});

相关标签:
4条回答
  • 2020-12-16 02:00

    It's creating an anonymous class.

    Note that within anonymous class, you can refer to final local variables from within the earlier code of the method, including final parameters:

    final String name = getName();
    
    Thread t = new Thread(new Runnable() {
        @Override public void run() {
            System.out.println(name);
        }
    });
    t.start();
    

    The values of the variables are passed into the constructor of the anonymous class. This is a weak form of closures (weak because of the restrictions: only values are copied, which is why the variable has to be final).

    0 讨论(0)
  • 2020-12-16 02:12

    It's called an Anonymous Class (PDF link).

    0 讨论(0)
  • 2020-12-16 02:18

    this is called anonymous classes in Java. It means that you create anonymous class that implements ISomeName interface and is passed as argument to methodA.

    0 讨论(0)
  • 2020-12-16 02:23

    This feature is called anonymous classes.

    0 讨论(0)
提交回复
热议问题