为什么我可以将接口用作匿名类?

huangapple go评论49阅读模式
英文:

Why can I use interface as anonymous class?

问题

例如:

Runnable r = new Runnable() {
    @Override
    public void run() {

    }
};

为什么没有错误?接口无法实例化。

英文:

For example:

Runnable r = new Runnable() {
    @Override
    public void run() {

    }
};

Why there is no error? Interfaces cannot be instantiated.

答案1

得分: 1

那个语法不是用来实例化东西的。或者至少,不仅仅是用来实例化的。

那个语法是语法糖(简写),等同于:

class Whatever$DontLookAtThisName implements Runnable {
    @Override public void run() {
    }
}
Runnable r = new Whatever$DontLookAtThisName();

如果你在那里使用了一个类,它会等同于 class Whatever$DontLookAtThis extends TheThingieYouPutThere,除了 extends FOOimplements FOO之外,概念是相同的。

英文:

That syntax isn't for instantiating things. Or at least, not just for that.

That syntax is sugar (short hand) for:

class Whatever$DontLookAtThisName implements Runnable {
    @Override public void run() {
    }
}
Runnable r = new Whatever$DontLookAtThisName();

Had you used a class there, it'd have been shortfor for class Whatever$DontLookAtThis extends TheThingieYouPutThere, but other than 'extends FOOvsimplements FOO`, it's the same concept.

答案2

得分: 0

你正在创建一个实现Runnable接口的匿名类。注意:由于此接口只有一个抽象方法,在Java 8及更高版本中,你可以这样做:

Runnable r = () -> System.out.println("run");
r.run();
英文:

You are creating an anonymous class that implements the Runnable interface. Note: That since this interface has a Single Abstract Method, in Java 8+ you could just do

Runnable r = () -> System.out.println("run");
r.run();

答案3

得分: 0

以下是已翻译的内容:

有关这个主题,Oracle 提供了一份很好的文档

> … 一个匿名类是一个表达式。匿名类表达式的语法类似于调用构造函数,不同之处在于代码块中包含了一个类定义。

匿名类表达式包括以下内容:

  • new 运算符

  • 要实现的接口名称或要继承的类名称。在此示例中,匿名类正在实现接口 [Runnable]。

  • 包含构造函数参数的括号,就像普通类实例创建表达式一样。注意:当你实现一个接口时,没有构造函数,所以你使用一对空括号,就像这个示例中的情况一样。

  • 一个类体,这是一个类声明体。更具体地说,在类体中,允许方法声明,但不允许语句。

英文:

There is a nice documentation from Oracle about this topic:

> ... an anonymous class is an expression. The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.

The anonymous class expression consists of the following:

  • The new operator

  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface [Runnable].

  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.

  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

huangapple
  • 本文由 发表于 2020年9月28日 01:39:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64091449.html
匿名

发表评论

匿名网友

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

确定