英文:
Can someone please explain an example from Eckel's "On Java 8" book regarding interfaces?
问题
在这个例子中,我对这一特定行进行了翻译:
RandomDoubles rd = new RandomDoubles() {};
这行代码创建了一个实现了RandomDoubles
接口的匿名类的对象,并将其赋值给变量rd
。这个匿名类实现了RandomDoubles
接口的next
方法。
在这个例子中,我们没有明确定义一个具体的类来实现RandomDoubles
接口,而是使用了匿名类的方式。这意味着我们在创建对象的同时实现了接口中的方法。这是一种常见的用法,特别是在需要一个简单的、一次性的实现时,可以使用匿名类来实现接口。
希望这有助于解释这行代码的作用。
英文:
So, we got such an example in which we are making a new interface RandomDoubles:
import java.util.*;
public interface RandomDoubles {
Random RAND = new Random(47);
default double next() { return RAND.nextDouble(); }
static void main(String[] args) {
RandomDoubles rd = new RandomDoubles() {};
for(int i = 0; i < 7; i ++)
System.out.print(rd.next() + " ");
}
}
/* Output:
0.7271157860730044 0.5309454508634242
0.16020656493302599 0.18847866977771732
0.5166020801268457 0.2678662084200585
0.2613610344283964
*/
`
and I'm confused with this particular line:
`RandomDoubles rd = new RandomDoubles() {};`
As I understand a variable of type of interface can reference an object of class which implemets that interface.
Where do we have in this example such an implementation? Why we got such reference in that particular line?
专注分享java语言的经验与见解,让所有开发者获益!
评论