简体   繁体   English

Java - 接口,实例化接口?

[英]Java - Interface, instantiating an interface?

So I just found this code example online a while ago and I'm going over it again but quite confused. 所以我刚刚在网上找到了这个代码示例,我再次讨论它但很困惑。

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. 通过查看它,我收集的内容(可能是错误的)是它将NumberPrinter类中的print方法传递给Printer对象。 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? 但是,该接口也称为Printer,因此我们不是要实例化Printer接口的匿名类,定义方法然后传递它吗?

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);
            }

        });
    }

}

This is called an anonymous inner class . 这称为匿名内部类

It creates an un-named class that implements the Printer interface. 它创建一个实现Printer接口的未命名类。

Your assumption is correct, and you cannot instantiate an interface. 您的假设是正确的,并且您无法实例化接口。 You can instantiate an anonymous class however, which is what the code is doing. 但是,您可以实例化一个匿名类,这就是代码正在执行的操作。

You need a Printer object for the print function of NumberPrinter. 您需要一个Printer对象来实现NumberPrinter的打印功能。 When you call that function you don't actually instantiate the Printer interface but you instantiate an implementation of it and this is why it's working. 当您调用该函数时,您实际上并未实例化Printer接口,而是实例化它的实现,这就是它工作的原因。

Your assumption was correct by the way. 顺便说一句,你的假设是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM