问题描述
所以我刚刚在网上找到了这个代码示例,我又重新审视它,但很困惑。
So I just found this code example online a while ago and I'm going over it again but quite confused.
从我看来,我收集的内容(可能是错误的)是它将NumberPrinter类中的print方法传递给Printer对象。但是,该接口也称为Printer,因此我们不是要实例化Printer接口的匿名类,定义方法然后传递它吗?
From looking at it, what I gather (and it might be wrong) is that it passes to the print method in the NumberPrinter class a Printer object. However, the interface is also called Printer, so aren't we instantiating an anonymous class of the Printer interface, defining the methods and then passing it?
我的基本问题是,我的初步假设是否正确?如果是这样我认为你无法实例化一个接口?
My basic question is, is my initial assumption correct? And if so I thought you could not instantiate an interface?
public class NumberPrinter {
public interface Printer {
public void print (int idx);
}
public static void print (Printer p) {
for (int i = 0; i < 4; i++) {
p.print(i);
}
}
public static void main(String[] args) {
print(new Printer() {
@Override
public void print(int idx) {
System.out.println(idx);
}
});
}
}
推荐答案
这称为匿名内部类。
它创建一个未命名的类来实现打印机
interface。
It creates an un-named class that implements the Printer
interface.
这篇关于Java - 接口,实例化接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!