Java API 显示实例化接口的示例

Java API shows an example which instantiates interface

我知道无法实例化 Java 接口。但是我正在阅读 Java API 中的匿名 class 解释,并找到了一个示例,其中包括创建接口的对象。这怎么可能? 部分代码:

public class HelloWorldAnonymousClasses {

interface HelloWorld {
 public void greet();
 public void greetSomeone(String someone); 
 }

 public void sayHello() {

class EnglishGreeting implements HelloWorld {

}

HelloWorld englishGreeting = new EnglishGreeting(); //object 1

HelloWorld frenchGreeting = new HelloWorld() {

String name = "tout le monde"; public void greet() { greetSomeone("mundo");} 
public void greetSomeone(String someone) {
name = someone; System.out.println("Hola, " + name);} }};

对象 englishGreeting 很好,因为对象类型是接口 HelloWorld 但引用转到对象类型 EnglishGreeting.

它不是在创建接口的实例,而是在创建实现 HelloWorld interfaceanonymous class 的实例。

如果您使用 javac 编译代码,您会看到编译器将为 anonymous class 生成 class 文件,看起来像

 HelloWorld.class

现在,如果您使用 javap 反编译生成的 class 文件,您将看到它实现了 HelloWorld

这是绝对允许的。
通过执行 new HelloWorld { /*abstracted methods here*/ },您并不是在创建接口的实例,而是在实现接口本身的匿名 class。 通过创建一个实现接口的单独 class 可以实现相同的结果,例如:

public class HelloWorldImplementation implements HelloWorld {
    /*abstracted methods here*/
}

也许这个例子对你有帮助。

public interface IFoo
{

}

IFoo foo = new IFoo {

};

foo指的是IFoo类型的空对象的内存。