java 类中定义方法,Java中的方法参数中的类定义?

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

object.methodA(new ISomeName() {

public void someMethod() {

//some code

}

});

Where ISomeName is an interface that has one method with the same signature as someMethod() above.

From what I can understand, we are defining a new nameclass class that implements ISomeName, creating an object of this class using default constructor and passing the object as an argument to methodA.

Is this right?

What is the name of this feature?

解决方案

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值