Java – interface, instantiation interface?
•
Java
So I just found this code example on the Internet. I discussed it again, but I was confused
By looking at it, what I collect (possibly wrong) is that it passes the print method in the numberprinter class to the printer object However, this interface is also called printer, so don't we instantiate the anonymous class of printer interface, define a method and pass it?
My basic question is, is my initial assumption correct? If so, I don't think you can 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); } }); } }
Solution
This is called an anonymous inner class
It creates an unnamed class that implements the printer interface
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码