Interface creating an interface?

So, I just found this sample code online a while ago, and I will go back to it again, but am confused.

From the look at it I am going to (and this may be wrong) is that it passes the Printer object to the printing method in the NumberPrinter class. However, the interface is also called a printer, so we do not create an anonymous printer interface class, define methods, and then pass it?

My main question is: is my initial guess correct? And if so, I thought you could not create 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); } }); } } 
+6
source share
3 answers

This is called an anonymous inner class.

Creates an unnamed class that implements the Printer interface.

+17
source

Your assumption is correct, and you cannot create an interface. However, you can instantiate an anonymous class, which is what the code does.

+3
source

You need a Printer object for the NumberPrinter print function. When you call this function, you are not actually creating an instance of the printer interface, but you are creating its implementation, which is why it works.

Your guess was right, by the way.

+1
source

Source: https://habr.com/ru/post/913474/


All Articles