有人能否请解释一下Eckel的《On Java 8》一书中关于接口的示例?

huangapple 未分类评论42阅读模式
英文:

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?

huangapple
  • 本文由 发表于 2020年4月4日 22:02:21
  • 转载请务必保留本文链接:https://java.coder-hub.com/61029249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定