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