我可以在Web上的几个例子中看到一个新的语法,这是一个例子:
Accumulator<Integer> sum = new Accumulator<Integer>(){
public Integer accumulate(Integer t1, Integer t2) {
return t1+t2;
}
};
Run Code Online (Sandbox Code Playgroud)
一般来说,{ a method }在创建一个类的实例之后写一个是什么意思?是什么东西的某种旧语法?
谢谢
您正在创建一个匿名内部类.
new Accumulator<Integer>() {
@Override
public Integer accumulate(Integer t1, Integer t2) {
return t1 + t2;
}
};
Run Code Online (Sandbox Code Playgroud)
定义匿名实现Accumulator.然后,您继续将此匿名类的引用分配给sum.
可以将其视为同时定义和分配实现的便捷方式.这是一种语法糖.
| 归档时间: |
|
| 查看次数: |
128 次 |
| 最近记录: |